"use client";

import { ArrowRight, Check, Eye, EyeOff, LockKeyhole, ShieldCheck, ShoppingBag, Sparkles, UserRound } from "lucide-react";
import { FormEvent, useState } from "react";
import { useTenant } from "@/components/tenant-provider";
import VoiceOtpPanel from "@/components/voice-otp-panel";

type SignupDetails = { name: string; email: string; phone: string; password: string };

export default function SignupClient() {
  const { tenant } = useTenant();
  const [step, setStep] = useState<"details" | "verify" | "success">("details");
  const [details, setDetails] = useState<SignupDetails>({ name: "", email: "", phone: "", password: "" });
  const [showPassword, setShowPassword] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState("");

  function continueToVerification(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    setError("");
    if (details.password.length < 8) {
      setError("Use at least 8 characters for your password.");
      return;
    }
    setStep("verify");
  }

  async function completeSignup(verificationToken: string) {
    setSubmitting(true);
    setError("");
    try {
      const response = await fetch("/api/auth/signup", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ ...details, verificationToken }),
      });
      const data = (await response.json()) as { error?: string };
      if (!response.ok) throw new Error(data.error || "Could not create your account.");
      setStep("success");
    } catch (reason) {
      setError(reason instanceof Error ? reason.message : "Could not create your account.");
    } finally {
      setSubmitting(false);
    }
  }

  return (
    <main className="min-h-[calc(100vh-72px)] bg-[#f4f7fb] px-4 py-10 sm:px-7 sm:py-16">
      <div className="mx-auto grid max-w-5xl overflow-hidden rounded-[32px] bg-white shadow-[0_24px_70px_rgba(12,40,90,0.14)] lg:grid-cols-[0.78fr_1.22fr]">
        <section className="relative overflow-hidden bg-[#071f4a] p-8 text-white sm:p-11">
          <div className="absolute -bottom-28 -left-24 h-72 w-72 rounded-full bg-[#155ee9]/50" />
          <div className="absolute right-[-80px] top-[-80px] h-64 w-64 rounded-full border-[40px] border-white/5" />
          <div className="relative">
            <span className="inline-flex items-center gap-2 rounded-full bg-[#ffd54a] px-3 py-1.5 text-[10px] font-black uppercase tracking-wider text-[#071f4a]"><Sparkles size={13} /> Join {tenant.brandName}</span>
            <h1 className="mt-6 text-4xl font-black leading-[1] tracking-[-0.045em]">One account.<br /><span className="text-[#ffd54a]">More happy shopping.</span></h1>
            <p className="mt-5 text-sm leading-6 text-blue-100">Save addresses, follow every delivery, receive offers and checkout faster with a verified mobile number.</p>
            <div className="mt-9 space-y-4">{["Voice-call mobile verification", "Live delivery tracking", "Personal deals and alerts", "Secure account protection"].map((item) => <p key={item} className="flex items-center gap-3 text-xs font-bold"><span className="grid h-6 w-6 place-items-center rounded-full bg-green-400 text-[#071f4a]"><Check size={13} strokeWidth={3} /></span>{item}</p>)}</div>
          </div>
        </section>

        <section className="p-6 sm:p-10 lg:p-12">
          <div className="mb-8 flex items-center gap-2">{["Account", "Verify", "Done"].map((label, index) => { const active = step === "details" ? index === 0 : step === "verify" ? index <= 1 : true; return <div key={label} className="flex flex-1 items-center gap-2"><span className={`grid h-7 w-7 shrink-0 place-items-center rounded-full text-[10px] font-black ${active ? "bg-[#155ee9] text-white" : "bg-slate-100 text-slate-400"}`}>{active && index < (step === "verify" ? 1 : step === "success" ? 2 : 0) ? <Check size={13} /> : index + 1}</span><span className={`hidden text-[10px] font-black sm:block ${active ? "text-[#155ee9]" : "text-slate-400"}`}>{label}</span>{index < 2 && <span className="h-px flex-1 bg-slate-200" />}</div>; })}</div>

          {step === "details" && <form onSubmit={continueToVerification}><div><p className="text-xs font-black uppercase tracking-[0.15em] text-[#155ee9]">Create account</p><h2 className="mt-2 text-2xl font-black tracking-tight">Tell us about yourself</h2><p className="mt-2 text-xs text-slate-500">Your mobile number will be verified by an automated voice call.</p></div><div className="mt-7 space-y-4"><label className="input-label">Full name<input required minLength={2} value={details.name} onChange={(event) => setDetails({ ...details, name: event.target.value })} className="checkout-input" placeholder="Aarav Sharma" /></label><label className="input-label">Email address<input required type="email" value={details.email} onChange={(event) => setDetails({ ...details, email: event.target.value })} className="checkout-input" placeholder="you@example.com" /></label><label className="input-label">Mobile number<input required type="tel" pattern="[0-9+ ]{10,16}" value={details.phone} onChange={(event) => setDetails({ ...details, phone: event.target.value })} className="checkout-input" placeholder={tenant.country === "Bangladesh" ? "+880 1711 470336" : "+91 98765 43210"} /></label><label className="input-label">Create password<div className="relative"><input required minLength={8} type={showPassword ? "text" : "password"} value={details.password} onChange={(event) => setDetails({ ...details, password: event.target.value })} className="checkout-input pr-11" placeholder="At least 8 characters" /><button type="button" onClick={() => setShowPassword((value) => !value)} className="absolute right-3 top-1/2 -translate-y-1/2 text-slate-400" aria-label="Toggle password visibility">{showPassword ? <EyeOff size={17} /> : <Eye size={17} />}</button></div></label><label className="flex items-start gap-2 text-[10px] leading-4 text-slate-500"><input required type="checkbox" className="mt-0.5 accent-[#155ee9]" />I agree to {tenant.brandName}&apos;s Terms of Use, Privacy Policy and voice verification call.</label></div>{error && <p className="mt-4 rounded-xl bg-red-50 p-3 text-xs font-bold text-red-600">{error}</p>}<button className="mt-6 flex w-full items-center justify-center gap-2 rounded-xl bg-[#155ee9] px-5 py-3.5 text-sm font-black text-white shadow-lg">Continue to mobile verification <ArrowRight size={17} /></button><p className="mt-5 text-center text-xs text-slate-500">Already registered? <a href="/" className="font-black text-[#155ee9]">Continue shopping</a></p></form>}

          {step === "verify" && <div><button onClick={() => setStep("details")} className="text-xs font-black text-[#155ee9]">← Edit account details</button><div className="mt-5"><p className="text-xs font-black uppercase tracking-[0.15em] text-[#155ee9]">Mobile security</p><h2 className="mt-2 text-2xl font-black tracking-tight">Listen for your code</h2><p className="mt-2 text-xs leading-5 text-slate-500">Text SMS is not available yet. Choose voice call and enter the code you hear.</p></div><div className="mt-7"><VoiceOtpPanel phone={details.phone} purpose="signup" onVerified={(token) => void completeSignup(token)} /></div>{submitting && <div className="mt-4 flex items-center justify-center gap-2 rounded-xl bg-slate-50 p-3 text-xs font-bold text-slate-500"><LockKeyhole size={15} /> Creating your secure account…</div>}{error && <p className="mt-4 rounded-xl bg-red-50 p-3 text-xs font-bold text-red-600">{error}</p>}</div>}

          {step === "success" && <div className="flex min-h-[460px] flex-col items-center justify-center text-center"><span className="relative grid h-24 w-24 place-items-center rounded-full bg-green-100 text-green-600"><UserRound size={43} /><span className="absolute -right-1 top-0 grid h-7 w-7 place-items-center rounded-full bg-green-600 text-white ring-4 ring-white"><Check size={14} strokeWidth={3} /></span></span><p className="mt-6 text-xs font-black uppercase tracking-[0.15em] text-green-600">Mobile verified</p><h2 className="mt-2 text-3xl font-black tracking-tight">Welcome to {tenant.brandName}, {details.name.split(" ")[0]}!</h2><p className="mt-3 max-w-sm text-sm leading-6 text-slate-500">Your account is ready. You can now shop, place verified orders and receive important updates.</p><a href="/#deals" className="mt-7 flex items-center gap-2 rounded-xl bg-[#155ee9] px-6 py-3.5 text-sm font-black text-white shadow-lg"><ShoppingBag size={17} /> Start shopping</a><p className="mt-5 flex items-center gap-1 text-[10px] text-slate-400"><ShieldCheck size={12} /> Account protected by verified mobile identity</p></div>}
        </section>
      </div>
    </main>
  );
}
