"use client";
import { useState } from "react";
import { Button, Field, Input, Select, api } from "./ui";
import { IndustrySelect, industryExamples } from "./industry-select";
import { AuthLayout } from "./auth-scene";
import { Eye, EyeOff, Lock, Mail } from "lucide-react";

export function AuthFrame({ title, subtitle, children, wide }: { title: string; subtitle?: string; children: React.ReactNode; wide?: boolean }) {
  return <AuthLayout title={title} subtitle={subtitle} wide={wide}>{children}</AuthLayout>;
}

export function LoginForm({ error, google, notice }: { error?: string; google: boolean; notice?: string }) {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [show, setShow] = useState(false);
  const [err, setErr] = useState(error ?? "");
  const [busy, setBusy] = useState(false);
  return (
    <form className="space-y-3" onSubmit={async (e) => {
      e.preventDefault(); setBusy(true); setErr("");
      try { const r = await api("/api/auth/login", { body: { email, password } }); window.location.href = r.next; } catch (x) { setErr((x as Error).message); setBusy(false); }
    }}>
      {notice && <p className="rounded-[12px] bg-ok/10 px-3 py-2 text-[12.5px] text-ok" role="status">{notice}</p>}
      <Field label="Email">
        <div className="relative"><Mail className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-ink-3" /><Input type="email" autoComplete="email" required value={email} onChange={(e) => setEmail(e.target.value)} placeholder="you@company.com" className="h-11 pl-9" /></div>
      </Field>
      <Field label={<span className="flex w-full items-center justify-between">Password<a href="/forgot-password" className="font-medium text-brand hover:underline">Forgot password?</a></span>}>
        <div className="relative"><Lock className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-ink-3" /><Input type={show ? "text" : "password"} autoComplete="current-password" required value={password} onChange={(e) => setPassword(e.target.value)} className="h-11 px-9" />
          <button type="button" onClick={() => setShow(!show)} className="absolute right-3 top-1/2 -translate-y-1/2 text-ink-3 hover:text-ink" aria-label={show ? "Hide password" : "Show password"}>{show ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}</button></div>
      </Field>
      {err && <p className="rounded-[12px] bg-bad/10 px-3 py-2 text-[12.5px] text-bad" role="alert">{err}</p>}
      <Button variant="primary" size="lg" className="w-full" loading={busy} type="submit">Sign in</Button>
      <p className="text-center text-[13px] text-ink-2">New here? <a href="/signup" className="font-semibold text-brand hover:underline">Create an account — 14-day free trial</a></p>
      {google && <>
        <div className="flex items-center gap-3 py-1 text-[11px] text-ink-3"><span className="h-px flex-1 bg-line" />or<span className="h-px flex-1 bg-line" /></div>
        <a href="/api/auth/google" className="flex h-11 w-full items-center justify-center gap-2 rounded-[12px] border border-white/80 bg-white/70 text-[13.5px] font-medium shadow-[0_2px_8px_-4px_rgb(15_23_42/.15)] hover:bg-white dark:border-white/10 dark:bg-white/5">
          <svg viewBox="0 0 48 48" className="h-4 w-4"><path fill="#FFC107" d="M43.6 20.5H42V20H24v8h11.3C33.7 32.7 29.2 36 24 36c-6.6 0-12-5.4-12-12s5.4-12 12-12c3.1 0 5.8 1.2 7.9 3.1l5.7-5.7C34 6.1 29.3 4 24 4 12.9 4 4 12.9 4 24s8.9 20 20 20 20-8.9 20-20c0-1.3-.1-2.4-.4-3.5z"/><path fill="#FF3D00" d="M6.3 14.7l6.6 4.8C14.7 15.1 19 12 24 12c3.1 0 5.8 1.2 7.9 3.1l5.7-5.7C34 6.1 29.3 4 24 4 16.3 4 9.7 8.3 6.3 14.7z"/><path fill="#4CAF50" d="M24 44c5.2 0 9.9-2 13.4-5.2l-6.2-5.2C29.2 35.1 26.7 36 24 36c-5.2 0-9.6-3.3-11.3-7.9l-6.5 5C9.5 39.6 16.2 44 24 44z"/><path fill="#1976D2" d="M43.6 20.5H42V20H24v8h11.3c-.8 2.2-2.2 4.2-4.1 5.6l6.2 5.2C37 39.2 44 34 44 24c0-1.3-.1-2.4-.4-3.5z"/></svg>
          Continue with Google
        </a>
      </>}
    </form>
  );
}

export function MfaForm() {
  const [code, setCode] = useState("");
  const [err, setErr] = useState("");
  const [busy, setBusy] = useState(false);
  return (
    <form className="space-y-3" onSubmit={async (e) => {
      e.preventDefault(); setBusy(true); setErr("");
      try { const r = await api("/api/auth/mfa", { body: { code } }); window.location.href = r.next; } catch (x) { setErr((x as Error).message); setBusy(false); }
    }}>
      <Field label="6-digit code from your authenticator app"><Input inputMode="numeric" autoFocus maxLength={8} value={code} onChange={(e) => setCode(e.target.value.replace(/\D/g, ""))} className="text-center font-mono text-[20px] tracking-[0.4em]" /></Field>
      {err && <p className="rounded-[7px] bg-bad/10 px-3 py-2 text-[12.5px] text-bad">{err}</p>}
      <Button variant="primary" size="lg" className="w-full" loading={busy} type="submit">Verify</Button>
    </form>
  );
}

export function SetupForm() {
  const [f, setF] = useState({ agencyName: "Brand Tempest", workspaceName: "", name: "", email: "", password: "", timezone: "Asia/Dhaka", currency: "BDT", locale: "en", industry: "general", token: "" });
  const [err, setErr] = useState("");
  const [busy, setBusy] = useState(false);
  const set = (k: keyof typeof f) => (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => setF({ ...f, [k]: e.target.value });
  return (
    <form className="space-y-3" onSubmit={async (e) => {
      e.preventDefault(); setBusy(true); setErr("");
      try {
        const res = await fetch("/api/auth/setup", { method: "POST", headers: { "Content-Type": "application/json", "x-setup-token": f.token }, body: JSON.stringify(f) });
        const j = await res.json();
        if (!res.ok) throw new Error(j.error?.message ?? "Setup failed");
        window.location.href = j.next;
      } catch (x) { setErr((x as Error).message); setBusy(false); }
    }}>
      <div className="grid grid-cols-2 gap-3">
        <Field label="Agency name"><Input required value={f.agencyName} onChange={set("agencyName")} /></Field>
        <Field label="First workspace (client)"><Input required value={f.workspaceName} onChange={set("workspaceName")} placeholder="e.g. Your company" /></Field>
        <Field label="Industry of this workspace" hint={industryExamples(f.industry) || "Sets the funnel, lead fields, AI questions and labels — change any time in Settings"}><IndustrySelect value={f.industry} onChange={(v) => setF({ ...f, industry: v })} /></Field>
      </div>
      <Field label="Your name"><Input required value={f.name} onChange={set("name")} /></Field>
      <Field label="Email"><Input type="email" required value={f.email} onChange={set("email")} /></Field>
      <Field label="Password" hint="At least 10 characters with letters and numbers"><Input type="password" required value={f.password} onChange={set("password")} /></Field>
      <div className="grid grid-cols-3 gap-3">
        <Field label="Timezone"><Select value={f.timezone} onChange={set("timezone")}><option>Asia/Dhaka</option><option>Australia/Sydney</option><option>Australia/Melbourne</option><option>America/New_York</option><option>America/Los_Angeles</option><option>UTC</option></Select></Field>
        <Field label="Currency"><Select value={f.currency} onChange={set("currency")}><option>BDT</option><option>USD</option><option>AUD</option></Select></Field>
        <Field label="Language"><Select value={f.locale} onChange={set("locale")}><option value="en">English</option><option value="bn">বাংলা</option></Select></Field>
      </div>
      <Field label="Setup token" hint="Only needed if SETUP_TOKEN is configured on the server"><Input value={f.token} onChange={set("token")} /></Field>
      {err && <p className="rounded-[7px] bg-bad/10 px-3 py-2 text-[12.5px] text-bad">{err}</p>}
      <Button variant="primary" size="lg" className="w-full" loading={busy} type="submit">Create workspace</Button>
    </form>
  );
}

export function InviteForm({ token, email }: { token: string; email: string }) {
  const [password, setPassword] = useState("");
  const [err, setErr] = useState("");
  const [busy, setBusy] = useState(false);
  return (
    <form className="space-y-3" onSubmit={async (e) => {
      e.preventDefault(); setBusy(true); setErr("");
      try { const r = await api("/api/auth/accept-invite", { body: { token, password } }); window.location.href = r.next; } catch (x) { setErr((x as Error).message); setBusy(false); }
    }}>
      <Field label="Email"><Input value={email} disabled /></Field>
      <Field label="Choose a password" hint="At least 10 characters with letters and numbers"><Input type="password" required value={password} onChange={(e) => setPassword(e.target.value)} /></Field>
      {err && <p className="rounded-[7px] bg-bad/10 px-3 py-2 text-[12.5px] text-bad">{err}</p>}
      <Button variant="primary" size="lg" className="w-full" loading={busy} type="submit">Join workspace</Button>
    </form>
  );
}

export function WorkspacePicker({ workspaces }: { workspaces: { id: string; name: string }[] }) {
  return (
    <div className="space-y-2">
      {workspaces.map((w) => (
        <button key={w.id} onClick={async () => { await api("/api/auth/workspace", { body: { workspaceId: w.id } }); window.location.href = "/dashboard"; }} className="flex w-full items-center justify-between rounded-[9px] border border-line px-3.5 py-3 text-left hover:border-brand/50 hover:bg-brand/5">
          <span className="font-medium">{w.name}</span><span className="text-brand">→</span>
        </button>
      ))}
      {!workspaces.length && <p className="text-[13px] text-ink-3">You don’t belong to any workspace yet. Ask an admin to invite you.</p>}
    </div>
  );
}
