"use client";

import { useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { ApiError, apiFetch } from "@/lib/apiClient";
import { useAuth } from "@/context/AuthContext";
import type { AuthResponse } from "@/types";

const LOGO =
  "https://lh3.googleusercontent.com/aida-public/AB6AXuBZLiDmj7R0A20k3lTZYq0jKXE5gPGYqcyUsXkhc6akG-b-uJXhEDZDUWCy4DigReUdiwk7iPZKy3_snSeM27u8vK3JWhd7xHLGDz8KLuOjFnItK4xmb1zgVUrEyYQl3shhg2Tlz2-zhoF3Dp6tuBa9V8WpINiArrDGn5uYd03avrz0qOcWCl37NGacVxxhkFT2XO4WUkcYiMT7Ols8G2h32EiI9YXL-QImMjWx50E-ujIfqVi7C--XMCfqhGgDli7AMR-pXuLUCxM";

const STEPS = [
  { id: 1, label: "You"     },
  { id: 2, label: "Contact" },
  { id: 3, label: "Secure"  },
];

const STEP_COPY = [
  { emoji: "🕌", heading: "What's your name?",    sub: "This is how we'll address you on your spiritual journey." },
  { emoji: "📲", heading: "How do we reach you?", sub: "We'll send booking updates and your OTP here." },
  { emoji: "🔐", heading: "Secure your account.", sub: "Choose a strong password — minimum 8 characters." },
];

function PasswordStrength({ password }: { password: string }) {
  const checks = [
    password.length >= 8,
    /[A-Z]/.test(password),
    /[0-9]/.test(password),
    /[^A-Za-z0-9]/.test(password),
  ];
  const score  = checks.filter(Boolean).length;
  const bars   = ["bg-red-400", "bg-orange-400", "bg-yellow-400", "bg-green-500"];
  const labels = ["Weak", "Fair", "Good", "Strong 🔥"];
  if (!password) return null;
  return (
    <div className="mt-2 space-y-1.5">
      <div className="flex gap-1">
        {[0, 1, 2, 3].map((i) => (
          <div key={i} className={`h-1 flex-1 rounded-full transition-all duration-300 ${i < score ? bars[score - 1] : "bg-[#e2e2e2]"}`} />
        ))}
      </div>
      {score > 0 && (
        <p className={`text-[11px] font-bold ${score <= 1 ? "text-red-500" : score === 2 ? "text-orange-500" : score === 3 ? "text-yellow-600" : "text-green-600"}`}>
          {labels[score - 1]}
        </p>
      )}
    </div>
  );
}

export default function RegisterPage() {
  const router = useRouter();
  const { login } = useAuth();
  const [step, setStep]       = useState(0);
  const [form, setForm]       = useState({ fullName: "", email: "", phone: "", password: "", confirm: "" });
  const [showPass, setShowPass] = useState(false);
  const [loading, setLoading]   = useState(false);
  const [error, setError]       = useState("");

  const set = (field: string) => (e: React.ChangeEvent<HTMLInputElement>) => {
    setError("");
    setForm((f) => ({ ...f, [field]: e.target.value }));
  };

  function nextStep(e: React.FormEvent) {
    e.preventDefault();
    setError("");
    if (step === 0 && !form.fullName.trim()) { setError("Please enter your full name."); return; }
    if (step === 1) {
      if (!form.email || !form.phone) { setError("Please fill in both fields."); return; }
      if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email)) { setError("Enter a valid email address."); return; }
    }
    if (step < 2) { setStep((s) => s + 1); return; }
    submitForm();
  }

  async function submitForm() {
    if (form.password !== form.confirm) { setError("Passwords don't match."); return; }
    if (form.password.length < 8) { setError("Password must be at least 8 characters."); return; }
    setLoading(true);
    try {
      const rawPhone = form.phone.replace(/^\+?234/, "").replace(/^0/, "");
      const phone = `+234${rawPhone}`;
      const data = await apiFetch<AuthResponse>("/auth/register", {
        method: "POST",
        body: JSON.stringify({ fullName: form.fullName, email: form.email, phone, password: form.password }),
        skipAuth: true,
      });
      login(data.accessToken, data.user);
      window.location.href = "/dashboard";
    } catch (err) {
      setError(err instanceof ApiError ? err.message : "Registration failed. Try again.");
    } finally {
      setLoading(false);
    }
  }

  const copy     = STEP_COPY[step];
  const progress = ((step + 1) / 3) * 100;

  const inputCls = "w-full py-4 bg-[#f7f7f7] border border-[#e2e2e2] rounded-2xl text-[#1a1c1c] placeholder-[#c6c5d3] text-[15px] font-medium focus:outline-none focus:border-[#D4AF37] focus:bg-white focus:ring-2 focus:ring-[#FED665]/20 transition-all";

  return (
    <main className="min-h-screen bg-[#f3f3f3] flex flex-col items-center justify-start px-4 py-8 relative overflow-hidden">

      {/* Background atmosphere */}
      <div className="fixed inset-0 -z-10 pointer-events-none">
        <div className="absolute top-0 left-1/2 -translate-x-1/2 w-[900px] h-[300px] bg-[#040b61]/5 blur-[120px] rounded-full" />
        <div className="absolute bottom-0 right-0 w-[500px] h-[400px] bg-[#FED665]/15 blur-[100px] rounded-full" />
        <div className="absolute bottom-0 left-0 w-[400px] h-[300px] bg-[#FED665]/10 blur-[120px] rounded-full" />
      </div>

      {/* ── Header ── */}
      <div className="w-full max-w-md mb-8">
        <div className="flex items-center justify-between mb-6">
          {step > 0 ? (
            <button
              onClick={() => { setError(""); setStep((s) => s - 1); }}
              className="w-10 h-10 rounded-full border border-[#c6c5d3] bg-white flex items-center justify-center text-[#464651] hover:border-[#040b61] hover:text-[#040b61] transition-all shadow-sm"
            >
              <span className="material-symbols-outlined text-lg">arrow_back</span>
            </button>
          ) : (
            <Link href="/" className="flex items-center gap-2.5">
              {/* eslint-disable-next-line @next/next/no-img-element */}
              <img src={LOGO} alt="Al-Bakkah" referrerPolicy="no-referrer" className="w-9 h-9 object-contain" />
              <span className="text-[#040b61] font-black text-[15px] tracking-tight hidden sm:block" style={{ fontFamily: "Plus Jakarta Sans, sans-serif" }}>Al-Bakkah</span>
            </Link>
          )}
          <Link href="/login" className="text-[#755b00] hover:text-[#040b61] transition-colors text-sm font-bold">
            Sign in
          </Link>
        </div>

        {/* Progress bar */}
        <div className="space-y-3">
          <div className="flex justify-between items-center">
            <span className="text-[#767682] text-[11px] font-bold uppercase tracking-[0.2em]">Step {step + 1} of 3</span>
            <span className="text-[#040b61] text-[11px] font-bold">{Math.round(progress)}%</span>
          </div>
          <div className="w-full h-1.5 bg-[#e2e2e2] rounded-full overflow-hidden">
            <div
              className="h-full rounded-full transition-all duration-500 ease-out"
              style={{ width: `${progress}%`, background: "linear-gradient(to right, #D4AF37, #FED665)" }}
            />
          </div>

          {/* Step dots */}
          <div className="flex items-center justify-center gap-2 pt-1">
            {STEPS.map((s, i) => (
              <div key={s.id} className="flex items-center gap-2">
                <div className="flex items-center gap-1.5">
                  <div className={`w-6 h-6 rounded-full flex items-center justify-center text-[10px] font-black transition-all ${
                    i < step   ? "bg-[#040b61] text-white" :
                    i === step ? "bg-[#FED665] text-[#040b61]" :
                                 "bg-[#e2e2e2] text-[#767682]"
                  }`}>
                    {i < step ? "✓" : s.id}
                  </div>
                  <span className={`text-[10px] font-bold uppercase tracking-wide hidden sm:block ${
                    i === step ? "text-[#040b61]" : "text-[#c6c5d3]"
                  }`}>{s.label}</span>
                </div>
                {i < STEPS.length - 1 && (
                  <div className={`w-5 h-px ${i < step ? "bg-[#040b61]/30" : "bg-[#e2e2e2]"}`} />
                )}
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* ── Card ── */}
      <div className="w-full max-w-md">
        <div className="bg-white rounded-[2rem] border border-[#e8e3d0] shadow-[0_12px_60px_-8px_rgba(4,11,97,0.12),0_4px_20px_-4px_rgba(254,214,101,0.15)] overflow-hidden">
          <div className="h-1 w-full" style={{ background: "linear-gradient(to right, #D4AF37, #FED665, #D4AF37)" }} />
          <div className="p-8">

          {/* Step hero */}
          <div className="text-center mb-8">
            <div className="text-5xl mb-4 select-none">{copy.emoji}</div>
            <h1
              className="text-[#040b61] font-black text-[24px] leading-tight mb-2"
              style={{ fontFamily: "Plus Jakarta Sans, sans-serif", letterSpacing: "-0.02em" }}
            >
              {copy.heading}
            </h1>
            <p className="text-[#767682] text-sm leading-relaxed">{copy.sub}</p>
          </div>

          {/* Error */}
          {error && (
            <div className="mb-5 flex items-center gap-3 p-4 rounded-2xl bg-red-50 border border-red-200">
              <span className="material-symbols-outlined text-red-500 text-lg shrink-0">error</span>
              <p className="text-red-600 text-sm font-medium">{error}</p>
            </div>
          )}

          <form onSubmit={nextStep} className="space-y-4">

            {/* Step 0 — Name */}
            {step === 0 && (
              <div className="relative group">
                <span className="material-symbols-outlined absolute left-4 top-1/2 -translate-y-1/2 text-[#c6c5d3] group-focus-within:text-[#D4AF37] transition-colors text-xl">badge</span>
                <input
                  type="text" required autoFocus autoComplete="name"
                  placeholder="Your full name"
                  value={form.fullName} onChange={set("fullName")}
                  className={`${inputCls} pl-12 pr-4`}
                />
              </div>
            )}

            {/* Step 1 — Email + Phone */}
            {step === 1 && (
              <>
                <div className="relative group">
                  <span className="material-symbols-outlined absolute left-4 top-1/2 -translate-y-1/2 text-[#c6c5d3] group-focus-within:text-[#D4AF37] transition-colors text-xl">mail</span>
                  <input
                    type="email" required autoFocus autoComplete="email"
                    placeholder="Email address"
                    value={form.email} onChange={set("email")}
                    className={`${inputCls} pl-12 pr-4`}
                  />
                </div>
                <div className="flex gap-3">
                  <div className="flex items-center gap-2 px-4 bg-[#f3f3f3] border border-[#e2e2e2] rounded-2xl shrink-0">
                    <span className="text-base">🇳🇬</span>
                    <span className="text-[#040b61] font-bold text-sm">+234</span>
                  </div>
                  <div className="relative flex-1 group">
                    <span className="material-symbols-outlined absolute left-4 top-1/2 -translate-y-1/2 text-[#c6c5d3] group-focus-within:text-[#D4AF37] transition-colors text-xl">call</span>
                    <input
                      type="tel" required autoComplete="tel"
                      placeholder="Phone number"
                      value={form.phone} onChange={set("phone")}
                      className={`${inputCls} pl-12 pr-4`}
                    />
                  </div>
                </div>
              </>
            )}

            {/* Step 2 — Password */}
            {step === 2 && (
              <>
                <div className="relative group">
                  <span className="material-symbols-outlined absolute left-4 top-1/2 -translate-y-1/2 text-[#c6c5d3] group-focus-within:text-[#D4AF37] transition-colors text-xl">lock</span>
                  <input
                    type={showPass ? "text" : "password"} required autoFocus minLength={8}
                    placeholder="Choose a password"
                    value={form.password} onChange={set("password")}
                    className={`${inputCls} pl-12 pr-12`}
                  />
                  <button type="button" onClick={() => setShowPass(!showPass)}
                    className="absolute right-4 top-1/2 -translate-y-1/2 text-[#c6c5d3] hover:text-[#464651] transition-colors">
                    <span className="material-symbols-outlined text-xl">{showPass ? "visibility_off" : "visibility"}</span>
                  </button>
                </div>
                <PasswordStrength password={form.password} />
                <div className="relative group">
                  <span className="material-symbols-outlined absolute left-4 top-1/2 -translate-y-1/2 text-[#c6c5d3] group-focus-within:text-[#D4AF37] transition-colors text-xl">lock_clock</span>
                  <input
                    type={showPass ? "text" : "password"} required
                    placeholder="Confirm password"
                    value={form.confirm} onChange={set("confirm")}
                    className={`${inputCls} pl-12 pr-12`}
                  />
                  {form.confirm && (
                    <span
                      className={`material-symbols-outlined absolute right-4 top-1/2 -translate-y-1/2 text-xl ${form.confirm === form.password ? "text-green-500" : "text-red-400"}`}
                      style={{ fontVariationSettings: "'FILL' 1" }}>
                      {form.confirm === form.password ? "check_circle" : "cancel"}
                    </span>
                  )}
                </div>
              </>
            )}

            {/* CTA */}
            <div className="pt-2">
              {step < 2 ? (
                <button type="submit"
                  className="w-full py-4 rounded-full bg-[#040b61] text-white font-bold text-[15px] hover:bg-[#0a1580] active:scale-[0.98] transition-all shadow-[0_4px_20px_rgba(4,11,97,0.25)] flex items-center justify-center gap-2">
                  Continue
                  <span className="material-symbols-outlined text-xl">arrow_forward</span>
                </button>
              ) : (
                <button type="submit" disabled={loading}
                  className="shimmer-btn w-full py-4 rounded-full font-bold text-[#040b61] text-[15px] hover:scale-[1.02] active:scale-[0.98] transition-transform disabled:opacity-60 disabled:scale-100 shadow-[0_8px_32px_rgba(254,214,101,0.35)] flex items-center justify-center gap-2">
                  {loading ? (
                    <>
                      <span className="w-5 h-5 border-2 border-[#040b61]/30 border-t-[#040b61] rounded-full animate-spin" />
                      Creating account…
                    </>
                  ) : "Begin My Journey ✨"}
                </button>
              )}
            </div>
          </form>

          {/* Trust perks — step 0 only */}
          {step === 0 && (
            <div className="mt-6 grid grid-cols-3 gap-3">
              {[
                { icon: "verified_user", label: "NAHCON Licensed" },
                { icon: "savings",       label: "Flexible Plan"   },
                { icon: "support_agent", label: "24/7 Support"    },
              ].map(({ icon, label }) => (
                <div key={label} className="flex flex-col items-center gap-2 p-3 rounded-2xl bg-[#f3f3f3] border border-[#e8e8e8]">
                  <span className="material-symbols-outlined text-[#040b61] text-lg" style={{ fontVariationSettings: "'FILL' 1" }}>{icon}</span>
                  <span className="text-[#767682] text-[10px] font-semibold text-center leading-tight">{label}</span>
                </div>
              ))}
            </div>
          )}
          </div>{/* closes p-8 */}
        </div>{/* closes card */}

        <p className="text-center text-[#767682] text-xs mt-6 leading-relaxed">
          Already have an account?{" "}
          <Link href="/login" className="text-[#755b00] font-bold hover:text-[#040b61] transition-colors">Sign in</Link>
          {" · "}
          <Link href="/terms" className="hover:text-[#040b61] transition-colors">Terms</Link>
          {" · "}
          <Link href="/privacy" className="hover:text-[#040b61] transition-colors">Privacy</Link>
        </p>
      </div>
    </main>
  );
}
