"use client";
import Link from "next/link";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { Alert, Field, call } from "../ui";

function useSubmit(url: string, after: (d: any) => void) {
  const [busy, setBusy] = useState(false), [err, setErr] = useState("");
  return { busy, err, submit: async (body: any) => { setBusy(true); setErr(""); const r = await call(url, body); setBusy(false); r.ok ? after(r.data) : setErr(r.error); } };
}
export function LoginForm({ next }: { next: string }) {
  const router = useRouter();
  const [f, setF] = useState({ email: "", password: "", code: "" }); const [need2fa, setNeed] = useState(false);
  const [human, setHuman] = useState<"idle" | "checking" | "ok">("idle"); const [tok, setTok] = useState("");
  const check = async () => { if (human !== "idle") return; setHuman("checking"); const r = await fetch("/api/auth/human", { cache: "no-store" }).then((x) => x.json()).catch(() => null); setTimeout(() => { if (r?.token) { setTok(r.token); setHuman("ok"); } else setHuman("idle"); }, 1300); };
  const { busy, err, submit } = useSubmit("/api/auth/login", (d) => { if (d.need2fa) return setNeed(true); router.replace(next || d.redirect); router.refresh(); });
  return (
    <div className="fixed inset-0 z-50 grid overflow-y-auto bg-[#0b0f19] text-white lg:grid-cols-2">
      <div className="relative hidden flex-col justify-between overflow-hidden p-12 lg:flex" style={{ background: "radial-gradient(60rem 30rem at 0% 0%, #1d4ed8 0%, transparent 60%), #0b0f19" }}>
        <Link href="/" className="flex items-center gap-3"><span className="grid h-10 w-10 place-items-center rounded-xl bg-blue-600 text-lg font-bold">O</span><span className="font-semibold">OXO Software Solution</span></Link>
        <div><h2 className="max-w-md text-4xl font-semibold leading-tight">Run your whole business from one calm place.</h2><p className="mt-4 max-w-md text-slate-400">Sales, clients, payments, projects, printing and support — the OXO Mother dashboard keeps everything in sync.</p></div>
        <p className="text-xs text-slate-500">Protected sign-in · encrypted sessions · optional 2-step verification</p>
      </div>
      <div className="grid place-items-center px-5 py-10"><form onSubmit={(e) => { e.preventDefault(); if (human !== "ok" && !need2fa) return; submit({ ...f, human: tok }); }} className="w-full max-w-sm space-y-4">
        <div><h1 className="text-2xl font-semibold">{need2fa ? "Two-step verification" : "Welcome back"}</h1><p className="mt-1 text-sm text-slate-400">{need2fa ? "Enter the 6-digit code from your authenticator app." : "Sign in to your OXO account."}</p></div>
        {!need2fa ? <>
          <label className="block text-sm"><span className="mb-1 block text-slate-300">Email</span><input className="w-full rounded-lg border border-white/10 bg-white/5 px-3.5 py-2.5 outline-none focus:border-blue-500" type="email" autoComplete="username" required autoFocus value={f.email} onChange={(e) => setF({ ...f, email: e.target.value })} /></label>
          <label className="block text-sm"><span className="mb-1 block text-slate-300">Password</span><input className="w-full rounded-lg border border-white/10 bg-white/5 px-3.5 py-2.5 outline-none focus:border-blue-500" type="password" autoComplete="current-password" required value={f.password} onChange={(e) => setF({ ...f, password: e.target.value })} /></label>
          <button type="button" onClick={check} className="flex w-full items-center gap-3 rounded-lg border border-white/10 bg-white/5 px-3.5 py-3 text-left text-sm" aria-pressed={human === "ok"}>
            <span className={`grid h-5 w-5 place-items-center rounded border ${human === "ok" ? "border-emerald-500 bg-emerald-500" : "border-slate-500"}`}>{human === "checking" ? <span className="h-3 w-3 animate-spin rounded-full border-2 border-slate-400 border-t-transparent" /> : human === "ok" ? "✓" : ""}</span>I’m not a robot<span className="ml-auto text-[10px] text-slate-500">human check</span></button></> :
          <input className="w-full rounded-lg border border-white/10 bg-white/5 px-3.5 py-3 text-center font-mono text-xl tracking-[.4em] outline-none focus:border-blue-500" inputMode="numeric" maxLength={6} autoFocus required value={f.code} onChange={(e) => setF({ ...f, code: e.target.value.replace(/\D/g, "") })} />}
        {err && <div role="alert" className="rounded-lg border border-rose-500/30 bg-rose-500/10 px-3 py-2 text-sm text-rose-300">{err}</div>}
        <button className="w-full rounded-lg bg-blue-600 py-2.5 font-semibold hover:bg-blue-500 disabled:opacity-50" disabled={busy || (!need2fa && human !== "ok")}>{busy ? "Signing in…" : need2fa ? "Verify" : "Unlock dashboard"}</button>
        <p className="text-center text-sm text-slate-400">New to OXO? <Link href="/register" className="font-semibold text-blue-400">Create an account</Link> · <Link href="/" className="hover:text-white">Website</Link></p>
      </form></div>
    </div>
  );
}
export function RegisterForm() {
  const router = useRouter();
  const [f, setF] = useState({ name: "", email: "", phone: "", company: "", password: "" });
  const { busy, err, submit } = useSubmit("/api/auth/register", (d) => { router.replace(d.redirect); router.refresh(); });
  return (
    <form onSubmit={(e) => { e.preventDefault(); submit(f); }} className="card space-y-4 p-7 shadow-xl">
      <div><h1 className="text-2xl font-extrabold tracking-tight">Create your account</h1><p className="text-sm text-slate-500">Get your own portal for products, payments and support.</p></div>
      <div className="grid gap-4 sm:grid-cols-2"><Field label="Full name"><input className="input" required value={f.name} onChange={(e) => setF({ ...f, name: e.target.value })} /></Field><Field label="Phone"><input className="input" inputMode="tel" value={f.phone} onChange={(e) => setF({ ...f, phone: e.target.value })} /></Field></div>
      <Field label="Business (optional)"><input className="input" value={f.company} onChange={(e) => setF({ ...f, company: e.target.value })} /></Field>
      <Field label="Email"><input className="input" type="email" autoComplete="username" required value={f.email} onChange={(e) => setF({ ...f, email: e.target.value })} /></Field>
      <Field label="Password" hint="8+ characters with a letter and a number."><input className="input" type="password" autoComplete="new-password" required minLength={8} value={f.password} onChange={(e) => setF({ ...f, password: e.target.value })} /></Field>
      <Alert>{err}</Alert><button className="btn btn-primary w-full" disabled={busy}>{busy ? "Creating…" : "Create account"}</button>
      <p className="text-center text-sm text-slate-500">Have an account? <Link href="/login" className="font-semibold text-brand">Sign in</Link></p>
    </form>
  );
}
