"use client";

/**
 * Self-service brisanje naloga — koristi se na javnoj stranici
 * `/privatnost/brisanje-naloga`. Radi i u Capacitor WebView-u i na web-u.
 *
 * Ulogovan korisnik: realna potvrda (lozinka ILI tačna e-mail adresa za
 * OAuth/magic naloge) → `POST /api/visitor-auth/delete` → nalog trajno
 * obrisan, redirect na početnu. Neulogovan: prikazuje se `fallback`
 * (email-zahtev blok) jer nema čega da se briše bez sesije.
 */

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";

type MeState =
  | { phase: "loading" }
  | { phase: "guest" }
  | { phase: "auth"; email: string };

export function AccountDeletionForm({
  fallback,
}: {
  fallback: React.ReactNode;
}) {
  const router = useRouter();
  const [me, setMe] = useState<MeState>({ phase: "loading" });
  const [password, setPassword] = useState("");
  const [confirmEmail, setConfirmEmail] = useState("");
  const [ack, setAck] = useState(false);
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState<string | null>(null);
  const [done, setDone] = useState(false);

  useEffect(() => {
    let cancelled = false;
    fetch("/api/visitor-auth/me", { cache: "no-store" })
      .then((r) => (r.ok ? r.json() : null))
      .then((data: { account: { email: string } | null } | null) => {
        if (cancelled) return;
        if (data?.account) {
          setMe({ phase: "auth", email: data.account.email });
        } else {
          setMe({ phase: "guest" });
        }
      })
      .catch(() => {
        if (!cancelled) setMe({ phase: "guest" });
      });
    return () => {
      cancelled = true;
    };
  }, []);

  async function onDelete(e: React.FormEvent) {
    e.preventDefault();
    setErr(null);
    setBusy(true);
    try {
      const res = await fetch("/api/visitor-auth/delete", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ password, confirmEmail }),
      });
      const data = (await res.json().catch(() => ({}))) as { error?: string };
      if (!res.ok) {
        throw new Error(data?.error || "Brisanje nije uspelo.");
      }
      setDone(true);
      setTimeout(() => {
        router.push("/?accountDeleted=1");
      }, 2200);
    } catch (caught) {
      setErr(caught instanceof Error ? caught.message : "Greška.");
      setBusy(false);
    }
  }

  if (me.phase === "loading") {
    return (
      <div className="surface mt-6 rounded-2xl bg-white p-6 text-sm text-[#0c1828]/60 sm:p-8">
        Učitavanje…
      </div>
    );
  }

  if (me.phase === "guest") {
    return <>{fallback}</>;
  }

  if (done) {
    return (
      <div className="mt-6 rounded-2xl border border-emerald-200 bg-emerald-50 p-6 text-center sm:p-8">
        <div className="mx-auto inline-flex h-12 w-12 items-center justify-center rounded-full bg-emerald-100 text-2xl text-emerald-700">
          ✓
        </div>
        <h2 className="mt-4 font-display text-xl font-bold text-emerald-800">
          Nalog je trajno obrisan
        </h2>
        <p className="mt-2 text-sm leading-7 text-emerald-700">
          Vaši lični podaci su uklonjeni. Preusmeravamo vas na početnu…
        </p>
      </div>
    );
  }

  return (
    <form
      onSubmit={onDelete}
      className="surface mt-6 rounded-2xl border border-rose-200 bg-white p-6 sm:p-8"
    >
      <p className="text-[0.62rem] font-extrabold uppercase tracking-[0.22em] text-rose-700">
        Brisanje odmah · prijavljeni ste kao {me.email}
      </p>
      <h2 className="mt-2 font-display text-2xl font-bold text-[#0c1828]">
        Trajno obriši moj nalog
      </h2>
      <p className="mt-3 text-[0.95rem] leading-[1.8] text-[#0c1828]/80">
        Ova radnja je <strong>nepovratna</strong>. Nalog, sačuvane pretrage,
        favoriti, poruke i push pretplate se brišu odmah. Javne recenzije
        ostaju, ali anonimizovane (bez vašeg imena i e-maila).
      </p>

      <div className="mt-5 space-y-3">
        <div>
          <label className="block text-xs font-bold text-[#374151]">
            Lozinka
          </label>
          <input
            type="password"
            autoComplete="current-password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            placeholder="Vaša lozinka"
            className="mt-1 w-full rounded-xl border border-[#ede8e3] bg-[#faf9f7] px-3.5 py-2.5 text-sm text-[#0c1828] outline-none focus:border-[#c2410c]/40 focus:bg-white"
          />
          <p className="mt-1 text-[0.7rem] text-[#9ca3af]">
            Ako koristite Google ili „magic link” prijavu, ostavite lozinku
            praznu i upišite e-mail naloga ispod radi potvrde identiteta.
          </p>
        </div>
        <div>
          <label className="block text-xs font-bold text-[#374151]">
            Potvrda e-mailom (za naloge bez lozinke)
          </label>
          <input
            type="email"
            autoComplete="off"
            value={confirmEmail}
            onChange={(e) => setConfirmEmail(e.target.value)}
            placeholder={me.email}
            className="mt-1 w-full rounded-xl border border-[#ede8e3] bg-[#faf9f7] px-3.5 py-2.5 text-sm text-[#0c1828] outline-none focus:border-[#c2410c]/40 focus:bg-white"
          />
        </div>
        <label className="flex items-start gap-2 text-xs leading-snug text-[#374151]">
          <input
            type="checkbox"
            checked={ack}
            onChange={(e) => setAck(e.target.checked)}
            className="mt-0.5 h-3.5 w-3.5 accent-rose-700"
          />
          <span>
            Razumem da je brisanje trajno i da se podaci ne mogu vratiti.
          </span>
        </label>
      </div>

      {err ? (
        <p className="mt-4 rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-xs font-semibold text-red-700">
          {err}
        </p>
      ) : null}

      <button
        type="submit"
        disabled={busy || !ack || (!password && !confirmEmail)}
        className="mt-5 inline-flex h-12 w-full items-center justify-center rounded-xl bg-rose-700 px-6 text-sm font-bold text-white transition hover:bg-rose-800 disabled:opacity-50 sm:w-auto"
      >
        {busy ? "Brišem…" : "Trajno obriši nalog"}
      </button>
    </form>
  );
}

export default AccountDeletionForm;
