"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";

type Step = "login" | "forgot" | "reset-sent";

export default function LoginPage() {
  const router = useRouter();
  const { login } = useAuth();

  const [step, setStep]         = useState<Step>("login");
  const [form, setForm]         = useState({ emailOrPhone: "", password: "", resetEmail: "" });
  const [showPass, setShowPass] = useState(false);
  const [loading, setLoading]   = useState(false);
  const [error, setError]       = useState("");
  const [successMsg, setSuccessMsg] = useState("");

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

  function goToStep(s: Step) { setStep(s); setError(""); }

  async function handleLogin(e: React.FormEvent) {
    e.preventDefault();
    setError("");
    setLoading(true);
    try {
      const data = await apiFetch<AuthResponse>("/auth/login", {
        method: "POST",
        body: JSON.stringify({ emailOrPhone: form.emailOrPhone, password: form.password }),
        skipAuth: true,
      });
      login(data.accessToken, data.user);
      window.location.href = data.user.role === "ADMIN" ? "/admin" : "/dashboard";
    } catch (err) {
      setError(err instanceof ApiError ? err.message : "Login failed. Try again.");
    } finally {
      setLoading(false);
    }
  }

  async function handleForgot(e: React.FormEvent) {
    e.preventDefault();
    setError("");
    setLoading(true);
    try {
      await apiFetch("/auth/forgot-password", {
        method: "POST",
        body: JSON.stringify({ email: form.resetEmail }),
        skipAuth: true,
      });
      setStep("reset-sent");
      setSuccessMsg(`A reset link was sent to ${form.resetEmail}`);
    } catch (err) {
      setError(err instanceof ApiError ? err.message : "Failed to send reset email.");
    } finally {
      setLoading(false);
    }
  }

  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-center 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 className="absolute top-1/3 left-0 w-[200px] h-[200px] bg-[#040b61]/4 blur-[80px] rounded-full" />
      </div>

      <div className="w-full max-w-md">

        {/* ── LOGIN ── */}
        {step === "login" && (
          <>
            {/* Logo row */}
            <div className="flex items-center justify-between mb-8">
              <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="/register" className="text-[#755b00] hover:text-[#040b61] transition-colors text-sm font-bold">
                Create account
              </Link>
            </div>

            {/* Card */}
            <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">

              {/* Gold top accent bar */}
              <div className="h-1 w-full" style={{ background: "linear-gradient(to right, #D4AF37, #FED665, #D4AF37)" }} />

              <div className="p-8">
                {/* Hero */}
                <div className="text-center mb-8">
                  {/* Logo icon with gold ring */}
                  <div className="relative w-16 h-16 mx-auto mb-5">
                    <div className="absolute inset-0 rounded-2xl bg-[#FED665]/20 blur-md" />
                    <div className="relative w-16 h-16 rounded-2xl bg-[#040b61] flex items-center justify-center shadow-[0_8px_24px_rgba(4,11,97,0.30)] ring-2 ring-[#FED665]/40">
                      {/* eslint-disable-next-line @next/next/no-img-element */}
                      <img src={LOGO} alt="" referrerPolicy="no-referrer" className="w-10 h-10 object-contain" />
                    </div>
                  </div>

                  <h1 className="text-[#040b61] font-black text-[24px] leading-tight mb-2"
                    style={{ fontFamily: "Plus Jakarta Sans, sans-serif", letterSpacing: "-0.02em" }}>
                    Welcome back
                  </h1>
                  <p className="text-[#767682] text-sm">Sign in to continue your journey.</p>
                </div>

                {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={handleLogin} className="space-y-4">
                  <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="text" required autoFocus autoComplete="username"
                      placeholder="Email or phone number"
                      value={form.emailOrPhone} onChange={set("emailOrPhone")}
                      className={`${inputCls} pl-12 pr-4`}
                    />
                  </div>

                  <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 autoComplete="current-password"
                      placeholder="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-[#D4AF37] transition-colors">
                      <span className="material-symbols-outlined text-xl">{showPass ? "visibility_off" : "visibility"}</span>
                    </button>
                  </div>

                  <div className="flex justify-end">
                    <button type="button" onClick={() => goToStep("forgot")}
                      className="text-[#755b00] hover:text-[#040b61] text-sm font-semibold transition-colors">
                      Forgot password?
                    </button>
                  </div>

                  <div className="pt-1">
                    <button type="submit" disabled={loading}
                      className="w-full py-4 rounded-full font-bold text-[15px] text-[#040b61] active:scale-[0.98] transition-all flex items-center justify-center gap-2 disabled:opacity-60 shimmer-btn shadow-[0_6px_24px_rgba(254,214,101,0.40)]">
                      {loading ? (
                        <>
                          <span className="w-5 h-5 border-2 border-[#040b61]/30 border-t-[#040b61] rounded-full animate-spin" />
                          Signing in…
                        </>
                      ) : (
                        <>
                          Sign In
                          <span className="material-symbols-outlined text-xl">arrow_forward</span>
                        </>
                      )}
                    </button>
                  </div>
                </form>

                {/* Divider */}
                <div className="my-6 flex items-center gap-3">
                  <div className="flex-1 h-px bg-[#e8e3d0]" />
                  <span className="text-[#D4AF37] text-xs font-bold tracking-wider">OR</span>
                  <div className="flex-1 h-px bg-[#e8e3d0]" />
                </div>

                <p className="text-center text-[#464651] text-sm">
                  Don&apos;t have an account?{" "}
                  <Link href="/register" className="text-[#755b00] font-bold hover:text-[#040b61] transition-colors">
                    Register free
                  </Link>
                </p>
              </div>
            </div>

            <p className="text-center text-[#767682] text-xs mt-6">
              <Link href="/terms" className="hover:text-[#040b61] transition-colors">Terms</Link>
              {" · "}
              <Link href="/privacy" className="hover:text-[#040b61] transition-colors">Privacy</Link>
            </p>
          </>
        )}

        {/* ── FORGOT PASSWORD ── */}
        {step === "forgot" && (
          <>
            <div className="flex items-center justify-between mb-8">
              <button onClick={() => goToStep("login")}
                className="w-10 h-10 rounded-full border border-[#e8e3d0] bg-white flex items-center justify-center text-[#464651] hover:border-[#D4AF37] hover:text-[#755b00] transition-all shadow-sm">
                <span className="material-symbols-outlined text-lg">arrow_back</span>
              </button>
              <span className="text-[#767682] text-sm font-semibold">Password reset</span>
            </div>

            <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 text-center">
                <div className="w-20 h-20 rounded-full flex items-center justify-center mx-auto mb-5"
                  style={{ background: "linear-gradient(135deg, #040b61, #1C2472)" }}>
                  <span className="material-symbols-outlined text-[#FED665] text-4xl" style={{ fontVariationSettings: "'FILL' 1" }}>support_agent</span>
                </div>
                <h1 className="text-[#040b61] font-black text-[22px] leading-tight mb-3"
                  style={{ fontFamily: "Plus Jakarta Sans, sans-serif", letterSpacing: "-0.02em" }}>
                  Forgot your password?
                </h1>
                <p className="text-[#767682] text-sm leading-relaxed mb-8">
                  Contact our support team on WhatsApp and we&apos;ll reset your password
                  within <strong className="text-[#040b61]">a few minutes</strong>.
                </p>

                <a
                  href="https://wa.me/2348077562271?text=Hello%2C%20I%20need%20help%20resetting%20my%20Al-Bakkah%20account%20password."
                  target="_blank"
                  rel="noopener noreferrer"
                  className="flex items-center justify-center gap-3 w-full py-4 rounded-full font-bold text-white text-[15px] transition-all active:scale-[0.98] shadow-lg mb-4"
                  style={{ background: "linear-gradient(135deg, #25D366, #128C7E)" }}
                >
                  <svg viewBox="0 0 24 24" className="w-5 h-5 fill-white shrink-0">
                    <path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347z"/>
                    <path d="M12 0C5.373 0 0 5.373 0 12c0 2.625.846 5.059 2.284 7.042L.785 23.24l4.299-1.378A11.945 11.945 0 0 0 12 24c6.627 0 12-5.373 12-12S18.627 0 12 0zm0 21.818a9.818 9.818 0 0 1-5.006-1.373l-.36-.214-3.716 1.192 1.21-3.624-.234-.372A9.818 9.818 0 1 1 12 21.818z"/>
                  </svg>
                  Chat on WhatsApp
                </a>

                <a href="tel:+2348077562271"
                  className="flex items-center justify-center gap-2 w-full py-3.5 rounded-full font-semibold text-[#040b61] text-sm border-2 border-[#040b61]/20 hover:bg-[#040b61]/5 transition-colors">
                  <span className="material-symbols-outlined text-lg" style={{ fontVariationSettings: "'FILL' 1" }}>call</span>
                  Call +234 807 756 2271
                </a>

                <p className="text-[#c6c5d3] text-xs mt-6">Available Mon – Sat · 8am – 6pm WAT</p>
              </div>
            </div>
          </>
        )}

        {/* ── RESET SENT ── */}
        {step === "reset-sent" && (
          <div className="bg-white rounded-[2rem] border border-[#e8e3d0] shadow-[0_12px_60px_-8px_rgba(4,11,97,0.12)] overflow-hidden text-center">
            <div className="h-1 w-full" style={{ background: "linear-gradient(to right, #D4AF37, #FED665, #D4AF37)" }} />
            <div className="p-10">
              <div className="w-20 h-20 rounded-full flex items-center justify-center mx-auto mb-6"
                style={{ background: "linear-gradient(135deg, #FED665/20, #FED665/10)", border: "2px solid #FED665" }}>
                <span className="material-symbols-outlined text-[#755b00] text-4xl" style={{ fontVariationSettings: "'FILL' 1" }}>mark_email_read</span>
              </div>
              <h2 className="text-[#040b61] font-black text-[22px] mb-3"
                style={{ fontFamily: "Plus Jakarta Sans, sans-serif", letterSpacing: "-0.02em" }}>
                Check your inbox
              </h2>
              <p className="text-[#464651] text-sm mb-1">{successMsg}</p>
              <p className="text-[#767682] text-xs mt-2">Link expires in 1 hour. Check spam if you don&apos;t see it.</p>
              <button onClick={() => goToStep("login")}
                className="mt-8 px-8 py-4 rounded-full font-bold text-sm text-[#040b61] shimmer-btn shadow-[0_6px_24px_rgba(254,214,101,0.40)] active:scale-[0.98] transition-all">
                Back to Sign In
              </button>
            </div>
          </div>
        )}

      </div>
    </main>
  );
}
