"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import { MessengerLogin } from "@/components/auth-modal";
import { AccountNavigation } from "@/components/account-navigation";
import { formatRestaurantDateTime } from "@/lib/date-time";

type HistoryState = {
  verified: boolean;
  phone: string | null;
  email: string | null;
  emailVerified: boolean;
  orders: { order_id: string; reference?: string; pending?: boolean; status: string; status_ru: string; paid: boolean; total: number | null; delivery_fee: number | null; due: string | null; created_at: string; track_url: string; public_ref: string; completed: boolean }[];
  bookings: { rid: string; dt: string; persons: number; status: string; status_ru?: string; name: string; created_at: string; public_ref: string; completed: boolean }[];
  error?: string;
};

function formatPhone(phone: string) {
  return `+${phone[0]} (${phone.slice(1, 4)}) ${phone.slice(4, 7)}-${phone.slice(7, 9)}-${phone.slice(9)}`;
}

export function AccountPanel({ displayName, suggestedName, profileComplete }: { displayName: string | null; suggestedName: string | null; profileComplete: boolean }) {
  const [history, setHistory] = useState<HistoryState | null>(null);
  const [phone, setPhone] = useState("");
  const [code, setCode] = useState("");
  const [codeSent, setCodeSent] = useState(false);
  const [cooldown, setCooldown] = useState(0);
  const [busy, setBusy] = useState(false);
  const [message, setMessage] = useState("");
  const [email, setEmail] = useState("");
  const [emailCode, setEmailCode] = useState("");
  const [emailCodeSent, setEmailCodeSent] = useState(false);
  const [emailCooldown, setEmailCooldown] = useState(0);
  const [profileName, setProfileName] = useState(displayName || suggestedName || "");
  const [profileCompleteState, setProfileCompleteState] = useState(profileComplete);

  async function loadHistory() {
    try {
      const response = await fetch("/api/account/history", { cache: "no-store" });
      const body = await response.json();
      if (!response.ok) throw new Error(body.error || "history_unavailable");
      setHistory(body);
    } catch { setHistory((value) => value ? { ...value, error: "history_unavailable" } : { verified: false, phone: null, email: null, emailVerified: false, orders: [], bookings: [], error: "history_unavailable" }); }
  }

  useEffect(() => { loadHistory(); }, []);
  useEffect(() => {
    if (cooldown <= 0) return;
    const timer = window.setTimeout(() => setCooldown((value) => value - 1), 1000);
    return () => window.clearTimeout(timer);
  }, [cooldown]);
  useEffect(() => {
    if (emailCooldown <= 0) return;
    const timer = window.setTimeout(() => setEmailCooldown((value) => value - 1), 1000);
    return () => window.clearTimeout(timer);
  }, [emailCooldown]);

  async function requestEmailCode(event: React.FormEvent) {
    event.preventDefault();
    if (busy || emailCooldown > 0) return;
    setBusy(true); setMessage("");
    try {
      const response = await fetch("/api/account/email/request", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ email }) });
      const body = await response.json();
      if (!response.ok) throw new Error(body.message || "Не удалось отправить код.");
      setEmailCodeSent(true); setEmailCooldown(60); setMessage(body.message || "Если эта почта привязана к номеру телефона, код отправлен.");
    } catch (error) { setMessage(error instanceof Error ? error.message : "Не удалось отправить код."); }
    finally { setBusy(false); }
  }

  async function verifyEmailCode(event: React.FormEvent) {
    event.preventDefault();
    if (busy) return;
    setBusy(true); setMessage("");
    try {
      const response = await fetch("/api/account/email/verify", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ email, code: emailCode }) });
      const body = await response.json();
      if (!response.ok) throw new Error(body.message || "Не удалось проверить код.");
      setMessage("Почта подтверждена.");
      setEmailCode(""); setEmailCodeSent(false);
      await loadHistory();
    } catch (error) { setMessage(error instanceof Error ? error.message : "Не удалось проверить код."); }
    finally { setBusy(false); }
  }

  async function requestCode(event: React.FormEvent) {
    event.preventDefault();
    if (busy || cooldown > 0) return;
    setBusy(true); setMessage("");
    try {
      const response = await fetch("/api/account/phone/request", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ phone }) });
      const body = await response.json();
      if (!response.ok) throw new Error(body.message || "Не удалось отправить код.");
      setCodeSent(true); setCooldown(60); setMessage("Код отправлен по SMS.");
    } catch (error) { setMessage(error instanceof Error ? error.message : "Не удалось отправить код."); }
    finally { setBusy(false); }
  }

  async function verifyCode(event: React.FormEvent) {
    event.preventDefault();
    if (busy) return;
    setBusy(true); setMessage("");
    try {
      const response = await fetch("/api/account/phone/verify", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ phone, code }) });
      const body = await response.json();
      if (!response.ok) throw new Error(body.message || "Не удалось проверить код.");
      setMessage("Телефон подтверждён.");
      setCode(""); setCodeSent(false);
      await loadHistory();
    } catch (error) { setMessage(error instanceof Error ? error.message : "Не удалось проверить код."); }
    finally { setBusy(false); }
  }

  async function saveName(event: React.FormEvent) {
    event.preventDefault(); setBusy(true); setMessage("");
    try {
      const response = await fetch("/api/account/profile", { method: "PATCH", headers: { "content-type": "application/json" }, body: JSON.stringify({ name: profileName }) });
      const body = await response.json();
      if (!response.ok) throw new Error(body.message || "Не удалось сохранить имя.");
      setProfileName(body.name); setProfileCompleteState(true); setMessage("Имя сохранено."); await loadHistory();
    } catch (error) { setMessage(error instanceof Error ? error.message : "Не удалось сохранить имя."); }
    finally { setBusy(false); }
  }

  return <div className="grid gap-6">
    {profileCompleteState ? <AccountNavigation active="profile" /> : null}
    <section className="card grid gap-4 p-5">
      <div><p className="eyebrow">{profileCompleteState ? "Имя" : "Завершение регистрации"}</p><h2 className="mt-1 text-2xl">{profileCompleteState ? "Как к вам обращаться" : "Подтвердите имя"}</h2></div>
      <form className="grid gap-3 sm:grid-cols-[1fr_auto]" onSubmit={saveName}>
        <input className="input" value={profileName} onChange={(event) => setProfileName(event.target.value)} minLength={2} maxLength={64} required autoFocus={!profileCompleteState} />
        <button className="button button-primary" disabled={busy || profileName.trim().length < 2}>{profileCompleteState ? "Изменить" : "Подтвердить"}</button>
      </form>
      <p className="text-sm text-kiln-milk/60">В дальнейшем имя можно изменить здесь без подтверждения через сторонние сервисы.</p>
    </section>
    {!profileCompleteState ? (message ? <p className="text-sm text-kiln-flame">{message}</p> : null) : <>
    <section className="card grid gap-4 p-5">
      <div><p className="eyebrow">Телефон</p><h2 className="mt-1 text-2xl">{history?.verified && history.phone ? formatPhone(history.phone) : "Подтверждение номера"}</h2></div>
      {history?.verified && history.phone ? (
        <p className="text-sm text-kiln-milk/60">Номер подтверждён — история заказов и бронирований доступна ниже.</p>
      ) : (
        <>
          <p className="text-sm text-kiln-milk/60">Для доступа к истории добровольно поделитесь номером в Telegram или MAX. Номер не публикуется в чате и передаётся сайту только после вашего подтверждения.</p>
          <div className="grid gap-2 sm:grid-cols-2">
            <MessengerLogin messenger="telegram" label="Telegram" requirePhone onDone={() => location.reload()} />
            <MessengerLogin messenger="max" label="MAX" requirePhone onDone={() => location.reload()} />
          </div>
        </>
      )}
      {message ? <p className="text-sm text-kiln-flame">{message}</p> : null}
    </section>
    <section className="card grid gap-4 p-5">
      <div><p className="eyebrow">Почта</p><h2 className="mt-1 text-2xl">{history?.emailVerified && history.email ? history.email : "Подтверждение почты"}</h2></div>
      {history?.emailVerified && history.email ? (
        <p className="text-sm text-kiln-milk/60">Почта подтверждена — на неё приходят подтверждения заказов и бронирований.</p>
      ) : (
        <>
          <p className="text-sm text-kiln-milk/60">Почту можно привязать только к кабинету с уже подтверждённым номером телефона. После привязки её можно использовать для входа.</p>
          <form className="grid gap-3 sm:grid-cols-[1fr_auto]" onSubmit={requestEmailCode}>
            <input className="input" type="email" placeholder="email@example.ru" value={email} onChange={(event) => setEmail(event.target.value)} required />
            <button className="button button-secondary" disabled={busy || emailCooldown > 0 || email.length < 5}>{emailCooldown > 0 ? `Повтор через ${emailCooldown} с` : emailCodeSent ? "Отправить ещё раз" : "Отправить код"}</button>
          </form>
          {emailCodeSent ? (
            <form className="grid gap-3 sm:grid-cols-[1fr_auto]" onSubmit={verifyEmailCode}>
              <input className="input" inputMode="numeric" placeholder="Код из письма" value={emailCode} onChange={(event) => setEmailCode(event.target.value)} required minLength={4} maxLength={10} />
              <button className="button button-primary" disabled={busy || emailCode.length < 4}>Подтвердить</button>
            </form>
          ) : null}
        </>
      )}
    </section>
    {history?.verified ? (
      <>
        <section className="card grid gap-3 p-5">
          <div><p className="eyebrow">История</p><h2 className="mt-1 text-2xl">Заказы</h2></div>
          {history.error ? <p className="text-sm text-kiln-flame">История временно недоступна. Попробуйте позже.</p> : null}
          {!history.error && !history.orders.length ? <p className="text-sm text-kiln-milk/60">Заказов пока нет.</p> : null}
          {history.orders.map((order) => <div key={order.reference || order.order_id} className="flex flex-wrap items-center justify-between gap-2 border-b border-white/10 pb-2 text-sm last:border-0">
            <Link className="text-kiln-flame underline" href={`/account/orders/${encodeURIComponent(order.reference || order.order_id)}`}>№{order.order_id} · {order.status_ru}{order.due ? ` · ко времени ${formatRestaurantDateTime(order.due)}` : ""}</Link>
            <span className="flex items-center gap-3"><strong className="whitespace-nowrap">{order.total === null ? "—" : order.total}{"\u00a0"}₽</strong>{order.paid ? <span className="text-kiln-flame">оплачен</span> : null}{order.track_url ? <a className="text-kiln-flame underline" href={order.track_url} target="_blank" rel="noreferrer">отслеживание</a> : null}</span>
          </div>)}
        </section>
        <section className="card grid gap-3 p-5">
          <div><p className="eyebrow">История</p><h2 className="mt-1 text-2xl">Бронирования</h2></div>
          {!history.bookings.length ? <p className="text-sm text-kiln-milk/60">Бронирований пока нет.</p> : null}
          {history.bookings.map((booking) => <div key={booking.rid} className="flex flex-wrap items-center justify-between gap-2 border-b border-white/10 pb-2 text-sm last:border-0">
            <Link className="text-kiln-flame underline" href={`/account/bookings/${encodeURIComponent(booking.rid)}`}>№{booking.rid} · {formatRestaurantDateTime(booking.dt)} · {booking.persons} чел.</Link>
            <span>{booking.status}</span>
          </div>)}
        </section>
      </>
    ) : null}</>}
  </div>;
}
