"use client";
/** Self-serve sign-up: account → verify email & phone (OTP) → business & industry → plan (14-day trial). */
import { useMemo, useState } from "react";
import { Check, CheckCircle2, Eye, EyeOff, Mail, Smartphone } from "lucide-react";
import { Button, Checkbox, Field, Input, Select, api, cx } from "./ui";
import { IndustrySelect, industryExamples } from "./industry-select";
import { PLANS_CATALOG, PLAN_ORDER, TRIAL_DAYS, type PlanKey } from "@/lib/plans";

const COUNTRIES = [
  { code: "880", label: "🇧🇩 +880", tz: "Asia/Dhaka", currency: "BDT" }, { code: "61", label: "🇦🇺 +61", tz: "Australia/Sydney", currency: "AUD" },
  { code: "1", label: "🇺🇸 +1", tz: "America/New_York", currency: "USD" }, { code: "44", label: "🇬🇧 +44", tz: "Europe/London", currency: "USD" },
  { code: "91", label: "🇮🇳 +91", tz: "Asia/Kolkata", currency: "USD" }, { code: "971", label: "🇦🇪 +971", tz: "Asia/Dubai", currency: "USD" },
];
const STEPS = ["Account", "Verify", "Business", "Plan"];

function strength(p: string) {
  let s = 0;
  if (p.length >= 10) s++; if (p.length >= 14) s++;
  if (/[a-z]/.test(p) && /[A-Z]/.test(p)) s++; if (/\d/.test(p)) s++; if (/[^A-Za-z0-9]/.test(p)) s++;
  return Math.min(s, 4);
}

export function SignupForm({ initialPlan }: { initialPlan?: string }) {
  const [step, setStep] = useState(0);
  const [f, setF] = useState({ name: "", email: "", country: "880", phone: "", password: "", accept: false });
  const [show, setShow] = useState(false);
  const [reg, setReg] = useState<{ registrationId: string; verify: { email: boolean; phone: boolean }; sentTo: { email: string; phone: string } } | null>(null);
  const [codes, setCodes] = useState({ email: "", phone: "" });
  const [verified, setVerified] = useState({ email: false, phone: false });
  const [biz, setBiz] = useState({ company: "", industry: "general", locale: "en" });
  const [plan, setPlan] = useState<PlanKey>(PLAN_ORDER.includes(initialPlan as PlanKey) ? (initialPlan as PlanKey) : "growth");
  const [err, setErr] = useState("");
  const [busy, setBusy] = useState("");
  const country = COUNTRIES.find((c) => c.code === f.country)!;
  const pwScore = useMemo(() => strength(f.password), [f.password]);

  const run = async (key: string, fn: () => Promise<void>) => { setBusy(key); setErr(""); try { await fn(); } catch (e) { setErr((e as Error).message); } finally { setBusy(""); } };
  const start = () => run("start", async () => {
    const r = await api("/api/auth/signup-start", { body: { name: f.name, email: f.email, phone: f.phone, password: f.password, country: f.country, acceptTerms: f.accept } });
    setReg(r); setVerified({ email: !r.verify.email, phone: !r.verify.phone }); setStep(1);
  });
  const verify = (channel: "email" | "phone") => run(`v-${channel}`, async () => {
    await api("/api/auth/signup-verify", { body: { registrationId: reg!.registrationId, channel, code: codes[channel] } });
    setVerified((v) => ({ ...v, [channel]: true }));
  });
  const resend = (channel: "email" | "phone") => run(`r-${channel}`, async () => { await api("/api/auth/signup-resend", { body: { registrationId: reg!.registrationId, channel } }); });
  const complete = () => run("complete", async () => {
    const r = await api("/api/auth/signup-complete", { body: { registrationId: reg!.registrationId, company: biz.company, industry: biz.industry, plan, timezone: country.tz, currency: country.currency, locale: biz.locale } });
    window.location.href = r.next;
  });

  return (
    <div>
      <ol className="mb-6 flex items-center gap-2" aria-label="Sign-up progress">
        {STEPS.map((s, i) => (
          <li key={s} className="flex flex-1 items-center gap-2">
            <span className={cx("grid h-7 w-7 shrink-0 place-items-center rounded-full text-[12px] font-bold transition", i < step ? "bg-ok text-white" : i === step ? "bg-brand text-white shadow-[0_6px_14px_-4px_rgb(var(--brand)/.7)]" : "bg-white/70 text-ink-3 dark:bg-white/10")}>{i < step ? <Check className="h-3.5 w-3.5" /> : i + 1}</span>
            <span className={cx("hidden text-[12px] font-medium sm:inline", i === step ? "text-ink" : "text-ink-3")}>{s}</span>
            {i < STEPS.length - 1 && <span className={cx("h-px flex-1", i < step ? "bg-ok" : "bg-line")} />}
          </li>
        ))}
      </ol>

      {step === 0 && (
        <form className="space-y-3" onSubmit={(e) => { e.preventDefault(); start(); }}>
          <Field label="Full name"><Input required autoComplete="name" value={f.name} onChange={(e) => setF({ ...f, name: e.target.value })} className="h-11" /></Field>
          <Field label="Work email"><Input required type="email" autoComplete="email" value={f.email} onChange={(e) => setF({ ...f, email: e.target.value })} placeholder="you@company.com" className="h-11" /></Field>
          <Field label="Mobile number" hint="We'll text a code to confirm it">
            <div className="flex gap-2">
              <Select value={f.country} onChange={(e) => setF({ ...f, country: e.target.value })} className="h-11 w-[112px]" aria-label="Country code">{COUNTRIES.map((c) => <option key={c.code} value={c.code}>{c.label}</option>)}</Select>
              <Input required type="tel" autoComplete="tel-national" inputMode="tel" value={f.phone} onChange={(e) => setF({ ...f, phone: e.target.value })} placeholder={f.country === "880" ? "01712 345678" : "Mobile number"} className="h-11 flex-1" />
            </div>
          </Field>
          <Field label="Password" hint="At least 10 characters with letters and numbers. Breached passwords are refused.">
            <div className="relative"><Input required type={show ? "text" : "password"} autoComplete="new-password" value={f.password} onChange={(e) => setF({ ...f, password: e.target.value })} className="h-11 pr-9" />
              <button type="button" onClick={() => setShow(!show)} className="absolute right-3 top-1/2 -translate-y-1/2 text-ink-3" aria-label={show ? "Hide password" : "Show password"}>{show ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}</button></div>
            <div className="mt-1.5 flex gap-1" aria-hidden>{[0, 1, 2, 3].map((i) => <span key={i} className={cx("h-1 flex-1 rounded-full", i < pwScore ? (pwScore >= 3 ? "bg-ok" : pwScore === 2 ? "bg-warn" : "bg-bad") : "bg-line")} />)}</div>
          </Field>
          <Checkbox checked={f.accept} onChange={(v) => setF({ ...f, accept: v })} label={<span className="text-[12.5px]">I agree to the <a href="/legal/terms" className="text-brand underline">Terms</a> and <a href="/legal/privacy" className="text-brand underline">Privacy Policy</a></span>} />
          {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 === "start"} type="submit" disabled={!f.accept}>Continue</Button>
          <p className="text-center text-[13px] text-ink-2">Already have an account? <a href="/login" className="font-semibold text-brand hover:underline">Sign in</a></p>
        </form>
      )}

      {step === 1 && reg && (
        <div className="space-y-4">
          <p className="text-[13px] text-ink-2">Enter the 6-digit codes we sent. They expire in 30 minutes.</p>
          {(["email", "phone"] as const).filter((c) => reg.verify[c]).map((c) => (
            <div key={c} className={cx("rounded-[18px] border p-4 transition", verified[c] ? "border-ok/40 bg-ok/5" : "border-white/80 bg-white/60 dark:border-white/10 dark:bg-white/5")}>
              <div className="mb-2 flex items-center gap-2 text-[13px] font-semibold">{c === "email" ? <Mail className="h-4 w-4 text-brand" /> : <Smartphone className="h-4 w-4 text-brand" />}{c === "email" ? "Email" : "Mobile"} <span className="font-normal text-ink-3">· {reg.sentTo[c]}</span>{verified[c] && <CheckCircle2 className="ml-auto h-5 w-5 text-ok" />}</div>
              {!verified[c] && (
                <div className="flex gap-2">
                  <Input autoComplete="one-time-code" inputMode="numeric" maxLength={6} value={codes[c]} onChange={(e) => setCodes({ ...codes, [c]: e.target.value.replace(/\D/g, "") })} placeholder="000000" className="h-11 flex-1 text-center font-mono text-[18px] tracking-[.35em]" aria-label={`${c} code`} />
                  <Button variant="primary" size="lg" loading={busy === `v-${c}`} disabled={codes[c].length !== 6} onClick={() => verify(c)}>Verify</Button>
                </div>
              )}
              {!verified[c] && <button className="mt-2 text-[12px] text-brand hover:underline disabled:opacity-50" disabled={!!busy} onClick={() => resend(c)}>{busy === `r-${c}` ? "Sending…" : "Resend code"}</button>}
            </div>
          ))}
          {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" disabled={!verified.email || !verified.phone} onClick={() => setStep(2)}>Continue</Button>
        </div>
      )}

      {step === 2 && (
        <form className="space-y-3" onSubmit={(e) => { e.preventDefault(); setStep(3); }}>
          <Field label="Company or brand name"><Input required value={biz.company} onChange={(e) => setBiz({ ...biz, company: e.target.value })} className="h-11" /></Field>
          <Field label="Your industry" hint={industryExamples(biz.industry) || "Your dashboard, funnel, lead fields and AI assistant are set up for it — change any time"}><IndustrySelect value={biz.industry} onChange={(v) => setBiz({ ...biz, industry: v })} /></Field>
          <Field label="Language"><Select value={biz.locale} onChange={(e) => setBiz({ ...biz, locale: e.target.value })}><option value="en">English</option><option value="bn">বাংলা (Bangla)</option></Select></Field>
          <p className="text-[12px] text-ink-3">Timezone {country.tz} · currency {country.currency} (from your phone number — change later in Settings).</p>
          <div className="flex gap-2"><Button size="lg" onClick={() => setStep(1)} type="button">Back</Button><Button variant="primary" size="lg" className="flex-1" type="submit" disabled={biz.company.trim().length < 2}>Continue</Button></div>
        </form>
      )}

      {step === 3 && (
        <div className="space-y-3">
          <p className="text-[13px] text-ink-2">Start free for {TRIAL_DAYS} days — no card needed. Pick a plan to continue with afterwards.</p>
          <div className="grid gap-2.5">
            {PLAN_ORDER.map((k) => {
              const p = PLANS_CATALOG[k];
              return (
                <button key={k} type="button" onClick={() => setPlan(k)} className={cx("relative rounded-[18px] border p-4 text-left transition-all", plan === k ? "border-brand bg-brand/5 shadow-[0_12px_28px_-16px_rgb(var(--brand)/.8)]" : "border-white/80 bg-white/60 hover:border-brand/40 dark:border-white/10 dark:bg-white/5")}>
                  {p.popular && <span className="absolute -top-2 right-4 rounded-full bg-gradient-to-r from-brand to-[#8B7CF6] px-2.5 py-0.5 text-[10.5px] font-bold text-white">Most popular</span>}
                  <div className="flex items-baseline justify-between"><span className="text-[15px] font-bold">{p.name}</span><span className="text-[20px] font-extrabold">${p.priceUsd}<span className="text-[12px] font-medium text-ink-3">/mo</span></span></div>
                  <p className="text-[12px] text-ink-3">{p.tagline}</p>
                  <ul className="mt-2 grid gap-0.5 text-[12px] text-ink-2">{p.highlights.slice(0, 4).map((h) => <li key={h} className="flex gap-1.5"><Check className="mt-0.5 h-3.5 w-3.5 shrink-0 text-brand" />{h}</li>)}</ul>
                </button>
              );
            })}
          </div>
          {err && <p className="rounded-[12px] bg-bad/10 px-3 py-2 text-[12.5px] text-bad" role="alert">{err}</p>}
          <div className="flex gap-2"><Button size="lg" onClick={() => setStep(2)}>Back</Button><Button variant="primary" size="lg" className="flex-1" loading={busy === "complete"} onClick={complete}>Start free trial</Button></div>
          <p className="text-center text-[11.5px] text-ink-3">Compare everything on the <a href="/pricing" className="text-brand underline">pricing page</a>.</p>
        </div>
      )}
    </div>
  );
}
