"use client";

import Link from "next/link";
import { useRouter } from "next/navigation";
import { useState } from "react";

import { TurnstileWidget } from "@/components/security/TurnstileWidget";
import { useSpamGuard } from "@/components/security/useSpamGuard";

type Mode = "login" | "register" | "magic-link";

const PRIVACY_HINT = (
  <p className="text-[0.65rem] leading-snug text-[#9ca3af]">
    Korišćenjem prihvatate{" "}
    <Link href="/privatnost" className="underline underline-offset-2 hover:text-[#c2410c]">
      Politiku privatnosti
    </Link>{" "}
    i{" "}
    <Link href="/uslovi-koriscenja" className="underline underline-offset-2 hover:text-[#c2410c]">
      Uslove korišćenja
    </Link>
    .
  </p>
);

type Props = {
  defaultMode?: Mode;
  redirectTo?: string;
  googleEnabled?: boolean;
};

export function AuthForm({ defaultMode = "login", redirectTo = "/nalog", googleEnabled = false }: Props) {
  const router = useRouter();
  const [mode, setMode] = useState<Mode>(defaultMode);
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [name, setName] = useState("");
  const [marketingOptIn, setMarketing] = useState(false);
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState<string | null>(null);
  const [magicSent, setMagicSent] = useState(false);
  const guard = useSpamGuard();

  async function syncFavoritesOnLogin() {
    // Best-effort: if user already had local favorites, push them up.
    try {
      const raw = window.localStorage.getItem("bp_favorites_v1");
      if (!raw) return;
      const items = JSON.parse(raw);
      if (!Array.isArray(items) || items.length === 0) return;
      const payload = items.map(
        (it: { type: string; id: string; title: string; path: string }) => ({
          entityType: it.type,
          entityId: it.id,
          title: it.title,
          path: it.path,
        }),
      );
      await fetch("/api/visitor-favorites/sync", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ items: payload }),
      });
    } catch {
      /* noop */
    }
  }

  async function onSubmit(e: React.FormEvent) {
    e.preventDefault();
    setErr(null);
    setBusy(true);

    try {
      if (mode === "magic-link") {
        const res = await fetch("/api/visitor-auth/magic-link", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            email,
            redirectTo,
            website_url: guard.honeypotValue,
            _bp_t: guard.token,
          }),
        });
        if (!res.ok) throw new Error("Greška pri slanju linka.");
        setMagicSent(true);
      } else if (mode === "login") {
        const res = await fetch("/api/visitor-auth/login", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            email,
            password,
            website_url: guard.honeypotValue,
            _bp_t: guard.token,
          }),
        });
        const data = await res.json().catch(() => ({}));
        if (!res.ok) throw new Error(data?.error || "Pogrešni podaci za prijavu.");
        await syncFavoritesOnLogin();
        router.replace(redirectTo);
        router.refresh();
      } else {
        const res = await fetch("/api/visitor-auth/register", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            email,
            password,
            name,
            marketingOptIn,
            website_url: guard.honeypotValue,
            _bp_t: guard.token,
          }),
        });
        const data = await res.json().catch(() => ({}));
        if (!res.ok) throw new Error(data?.error || "Greška pri registraciji.");
        await syncFavoritesOnLogin();
        router.replace(redirectTo);
        router.refresh();
      }
    } catch (caught) {
      setErr(caught instanceof Error ? caught.message : "Greška.");
    } finally {
      setBusy(false);
    }
  }

  const inputCls =
    "w-full rounded-xl border border-[#ede8e3] bg-[#faf9f7] px-3.5 py-2.5 text-sm text-[#0c1828] placeholder:text-[#9ca3af] outline-none transition focus:border-[#c2410c]/40 focus:bg-white focus:ring-2 focus:ring-[#c2410c]/15";

  if (magicSent) {
    return (
      <div className="rounded-2xl border border-emerald-200 bg-emerald-50 p-6 text-center">
        <div className="mx-auto inline-flex h-12 w-12 items-center justify-center rounded-full bg-emerald-100 text-emerald-700">
          ✓
        </div>
        <h3 className="mt-4 font-display text-lg font-bold text-emerald-800">Proverite e-mail</h3>
        <p className="mt-2 text-sm leading-7 text-emerald-700">
          Poslali smo link za prijavu na <strong>{email}</strong>. Link važi 30 minuta.
        </p>
        <button
          type="button"
          onClick={() => {
            setMagicSent(false);
            setMode("login");
          }}
          className="mt-4 text-xs font-bold text-emerald-700 underline"
        >
          Nazad
        </button>
      </div>
    );
  }

  return (
    <form onSubmit={onSubmit} className="space-y-3">
      {/* Honeypot */}
      <div
        aria-hidden="true"
        className="pointer-events-none"
        style={{ position: "absolute", left: "-9999px", top: "-9999px", height: 0, width: 0, overflow: "hidden", opacity: 0 }}
      >
        <input
          type="text"
          name="website_url"
          tabIndex={-1}
          autoComplete="off"
          value={guard.honeypotValue}
          onChange={(e) => guard.setHoneypotValue(e.target.value)}
        />
      </div>

      {/* Mode tabs */}
      <div className="flex rounded-full border border-[#ede8e3] bg-[#faf9f7] p-1">
        {(["login", "register"] as const).map((m) => (
          <button
            key={m}
            type="button"
            onClick={() => {
              setMode(m);
              setErr(null);
            }}
            className={`flex-1 rounded-full px-4 py-1.5 text-xs font-bold transition ${
              mode === m ? "bg-white text-[#0c1828] shadow-sm" : "text-[#6b7280]"
            }`}
          >
            {m === "login" ? "Prijava" : "Registracija"}
          </button>
        ))}
      </div>

      {googleEnabled && (
        <>
          <a
            href={`/api/visitor-auth/oauth/google/start?redirectTo=${encodeURIComponent(redirectTo)}`}
            className="flex w-full items-center justify-center gap-3 rounded-xl border border-[#ede8e3] bg-white px-4 py-2.5 text-sm font-bold text-[#0c1828] transition hover:border-[#c2410c]/30 hover:bg-[#fff4f0]"
          >
            <svg width="18" height="18" viewBox="0 0 48 48" aria-hidden="true">
              <path fill="#FFC107" d="M43.611 20.083H42V20H24v8h11.303c-1.649 4.657-6.08 8-11.303 8-6.627 0-12-5.373-12-12s5.373-12 12-12c3.059 0 5.842 1.154 7.961 3.039l5.657-5.657C34.046 6.053 29.268 4 24 4 12.955 4 4 12.955 4 24s8.955 20 20 20 20-8.955 20-20c0-1.341-.138-2.65-.389-3.917z" />
              <path fill="#FF3D00" d="M6.306 14.691l6.571 4.819C14.655 15.108 18.961 12 24 12c3.059 0 5.842 1.154 7.961 3.039l5.657-5.657C34.046 6.053 29.268 4 24 4 16.318 4 9.656 8.337 6.306 14.691z" />
              <path fill="#4CAF50" d="M24 44c5.166 0 9.86-1.977 13.409-5.192l-6.19-5.238C29.211 35.091 26.715 36 24 36c-5.202 0-9.619-3.317-11.283-7.946l-6.522 5.025C9.505 39.556 16.227 44 24 44z" />
              <path fill="#1976D2" d="M43.611 20.083H42V20H24v8h11.303c-.792 2.237-2.231 4.166-4.087 5.571.001-.001.002-.001.003-.002l6.19 5.238C36.971 39.205 44 34 44 24c0-1.341-.138-2.65-.389-3.917z" />
            </svg>
            Nastavite sa Google nalogom
          </a>
          <div className="relative my-3">
            <div className="absolute inset-0 flex items-center">
              <span className="w-full border-t border-[#ede8e3]" />
            </div>
            <div className="relative flex justify-center text-[0.65rem] font-bold uppercase tracking-[0.16em]">
              <span className="bg-white px-2 text-[#9ca3af]">ili</span>
            </div>
          </div>
        </>
      )}

      {mode === "register" && (
        <input
          type="text"
          autoComplete="name"
          placeholder="Ime i prezime (opciono)"
          value={name}
          onChange={(e) => setName(e.target.value)}
          className={inputCls}
        />
      )}

      <input
        type="email"
        autoComplete="email"
        required
        placeholder="E-mail"
        value={email}
        onChange={(e) => setEmail(e.target.value)}
        className={inputCls}
      />

      {mode !== "magic-link" && (
        <input
          type="password"
          autoComplete={mode === "register" ? "new-password" : "current-password"}
          required
          minLength={8}
          placeholder="Lozinka (najmanje 8 znakova)"
          value={password}
          onChange={(e) => setPassword(e.target.value)}
          className={inputCls}
        />
      )}

      {mode === "register" && (
        <label className="flex items-start gap-2 text-xs leading-snug text-[#374151]">
          <input
            type="checkbox"
            checked={marketingOptIn}
            onChange={(e) => setMarketing(e.target.checked)}
            className="mt-0.5 h-3.5 w-3.5 accent-[#c2410c]"
          />
          <span>Pošaljite mi povremene novosti, top oglase i preporuke (newsletter).</span>
        </label>
      )}

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

      <TurnstileWidget onToken={guard.setTurnstileToken} />

      <button
        type="submit"
        disabled={busy || !guard.ready}
        className="flex w-full items-center justify-center gap-2 rounded-xl bg-[#c2410c] px-4 py-3 text-sm font-bold text-white transition hover:bg-[#d94e22] active:scale-[0.97] disabled:opacity-60"
      >
        {busy
          ? "Šaljem..."
          : mode === "register"
            ? "Otvori nalog"
            : mode === "login"
              ? "Prijavi se"
              : "Pošalji magic link"}
      </button>

      <button
        type="button"
        onClick={() => {
          setMode(mode === "magic-link" ? "login" : "magic-link");
          setErr(null);
        }}
        className="block w-full text-center text-xs font-semibold text-[#6b7280] hover:text-[#c2410c]"
      >
        {mode === "magic-link" ? "Prijava lozinkom" : "Prijavi se bez lozinke (magic link)"}
      </button>

      {PRIVACY_HINT}
    </form>
  );
}
