"use client";

import { useState, useRef, useEffect } from "react";
import Link from "next/link";
import Image from "next/image";
import { useRouter } from "next/navigation";
import gsap from "gsap";
import { EnvelopeSimple, Lock, ArrowRight, ArrowLeft, User, Phone } from "@phosphor-icons/react";
import { useLanguage } from "@/lib/i18n/context";

type Mode = "login" | "register";

export default function AuthPage({ initialMode = "login" }: { initialMode?: Mode }) {
  const { t, locale } = useLanguage();
  const isRTL = locale === "ar";
  const router    = useRouter();
  const [mode, setMode] = useState<Mode>(initialMode);

  const imageRef  = useRef<HTMLDivElement>(null);
  const formRef   = useRef<HTMLDivElement>(null);
  const fieldsRef = useRef<HTMLDivElement>(null);

  // Login state
  const [loginForm,    setLoginForm]    = useState({ identifier: "", password: "" });
  const [loginError,   setLoginError]   = useState("");
  const [loginLoading, setLoginLoading] = useState(false);

  // Register state
  const [regForm,    setRegForm]    = useState({ prenom: "", nom: "", email: "", password: "", phone: "" });
  const [regError,   setRegError]   = useState("");
  const [regLoading, setRegLoading] = useState(false);

  // Set initial panel positions if starting in register mode
  useEffect(() => {
    if (initialMode === "register" && window.innerWidth >= 1024) {
      gsap.set(imageRef.current, { x: "100%" });
      gsap.set(formRef.current,  { x: "-100%" });
    }
  }, []); // eslint-disable-line react-hooks/exhaustive-deps

  const switchTo = (newMode: Mode) => {
    if (newMode === mode) return;
    const toRegister = newMode === "register";
    const isDesktop  = window.innerWidth >= 1024;

    const tl = gsap.timeline();

    // Fade fields out
    tl.to(fieldsRef.current, { opacity: 0, y: 10, duration: 0.2, ease: "power2.in" }, 0);

    // Slide panels on desktop
    if (isDesktop) {
      tl.to(imageRef.current, { x: toRegister ? "100%" : "0%", duration: 0.65, ease: "power3.inOut" }, 0.05);
      tl.to(formRef.current,  { x: toRegister ? "-100%" : "0%", duration: 0.65, ease: "power3.inOut" }, 0.05);
    }

    // Swap content mid-slide
    tl.call(() => setMode(newMode), undefined, isDesktop ? 0.35 : 0.15);

    // Fade fields in
    tl.fromTo(
      fieldsRef.current,
      { opacity: 0, y: -10 },
      { opacity: 1, y: 0, duration: 0.25, ease: "power2.out" },
      isDesktop ? 0.55 : 0.25
    );
  };

  const submitLogin = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoginError("");
    setLoginLoading(true);
    try {
      const res  = await fetch("/api/customer/login", {
        method: "POST", headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ identifier: loginForm.identifier, password: loginForm.password }),
      });
      const data = await res.json();
      if (!res.ok) {
        if (data.code === "EMAIL_NOT_VERIFIED") {
          router.push(`/verify-email?email=${encodeURIComponent(loginForm.identifier)}`);
          return;
        }
        setLoginError(data.error);
        return;
      }
      router.push("/produits");
      router.refresh();
    } finally { setLoginLoading(false); }
  };

  const submitRegister = async (e: React.FormEvent) => {
    e.preventDefault();
    setRegError("");
    setRegLoading(true);
    try {
      const res  = await fetch("/api/customer/register", {
        method: "POST", headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ ...regForm, name: `${regForm.prenom} ${regForm.nom}`.trim() }),
      });
      const data = await res.json();
      if (!res.ok) { setRegError(data.error); return; }
      router.push(`/verify-email?email=${encodeURIComponent(regForm.email)}`);
    } finally { setRegLoading(false); }
  };

  const inputClass =
    "w-full bg-brand-sand-light border border-brand-dark/10 rounded-2xl px-4 py-3.5 text-brand-dark text-sm placeholder-brand-dark/30 focus:outline-none focus:border-brand-yellow focus:bg-white transition-colors";

  return (
    <main className="min-h-screen lg:h-screen lg:overflow-hidden relative bg-brand-off-white">

      {/* ── Yellow / illustration panel ── */}
      <div
        ref={imageRef}
        className="hidden lg:flex absolute top-0 left-0 w-1/2 h-full bg-brand-sand-light flex-col items-center justify-between py-14 px-12 z-10"
      >
        <Link href="/" className="self-start">
          <Image src="/logo.png" alt="Asli Food" width={180} height={72} className="h-20 w-auto object-contain" />
        </Link>

        <div className="relative w-80 h-80 flex-shrink-0">
          <Image
            src={mode === "login" ? "/illustration/3.png" : "/illustration/1.png"}
            alt=""
            fill
            sizes="320px"
            className="object-contain"
            style={{ mixBlendMode: "multiply" }}
          />
        </div>

        <div className="self-start">
          <p
            className="text-brand-dark text-3xl font-bold leading-tight"
            style={{ fontFamily: "var(--font-space, sans-serif)" }}
          >
            {t.auth.tagline.split("\n").map((line, i) => (
              <span key={i}>{line}{i === 0 && <br />}</span>
            ))}
          </p>
          <p className="text-brand-dark/50 text-sm mt-2">
            {t.auth.taglineSub}
          </p>
        </div>
      </div>

      {/* ── Form panel ── */}
      <div
        ref={formRef}
        className={`flex flex-col justify-center min-h-screen px-8 sm:px-12 lg:absolute lg:top-0 lg:left-[50%] lg:w-1/2 lg:h-full lg:min-h-0 lg:px-16 ${isRTL ? "py-6" : "py-12"}`}
      >
        {/* Mobile logo */}
        <div className="lg:hidden flex justify-center mb-10">
          <Link href="/">
            <Image src="/logo.png" alt="Asli Food" width={180} height={180} className="rounded-3xl" />
          </Link>
        </div>

        <div className="w-full max-w-sm mx-auto">

          <Link
            href="/"
            className="inline-flex items-center gap-1.5 text-brand-dark/35 text-xs font-semibold hover:text-brand-dark transition-colors mb-10"
          >
            {t.auth.home}
          </Link>

          {/* Animated content */}
          <div ref={fieldsRef}>
            {mode === "login" ? (
              <>
                <h1
                  className="text-brand-dark text-3xl font-bold mb-1"
                  style={{ fontFamily: "var(--font-space, sans-serif)" }}
                >
                  {t.auth.login.title}
                </h1>
                <p className={`text-brand-dark/40 text-sm ${isRTL ? "mb-5" : "mb-8"}`}>
                  {t.auth.login.sub}
                </p>

                <form onSubmit={submitLogin} className={isRTL ? "space-y-3" : "space-y-4"}>
                  <Field label={t.auth.login.identifier} icon={<EnvelopeSimple size={12} weight="bold" />}>
                    <input
                      type="text" required autoComplete="username"
                      value={loginForm.identifier} placeholder={t.auth.login.identifierPh}
                      onChange={e => setLoginForm(f => ({ ...f, identifier: e.target.value }))}
                      className={inputClass}
                    />
                  </Field>
                  <Field label={t.auth.login.password} icon={<Lock size={12} weight="bold" />}>
                    <input
                      type="password" required autoComplete="current-password"
                      value={loginForm.password} placeholder="••••••••"
                      onChange={e => setLoginForm(f => ({ ...f, password: e.target.value }))}
                      className={inputClass}
                    />
                  </Field>
                  <div className="flex justify-end">
                    <a href="/forgot-password" className="text-brand-dark/35 text-xs hover:text-brand-dark transition-colors">
                      {t.auth.login.forgot}
                    </a>
                  </div>

                  {loginError && (
                    <p className="text-red-500 text-sm bg-red-50 border border-red-200 rounded-2xl px-4 py-3">
                      {loginError}
                    </p>
                  )}

                  <button
                    type="submit" disabled={loginLoading}
                    className="w-full flex items-center justify-center gap-2 bg-brand-dark text-brand-yellow font-bold py-4 rounded-2xl text-sm tracking-wide hover:bg-brand-yellow hover:text-brand-dark disabled:opacity-50 transition-all duration-300 mt-2"
                  >
                    {loginLoading ? t.auth.login.loading : t.auth.login.submit}
                    {!loginLoading && (isRTL ? <ArrowLeft size={15} weight="bold" /> : <ArrowRight size={15} weight="bold" />)}
                  </button>
                </form>

                <p className="text-center text-brand-dark/35 text-sm mt-8">
                  {t.auth.login.noAccount}{" "}
                  <button
                    onClick={() => switchTo("register")}
                    className="text-brand-dark font-bold hover:text-brand-yellow transition-colors"
                  >
                    {t.auth.login.register}
                  </button>
                </p>
              </>
            ) : (
              <>
                <h1
                  className="text-brand-dark text-3xl font-bold mb-1"
                  style={{ fontFamily: "var(--font-space, sans-serif)" }}
                >
                  {t.auth.register.title}
                </h1>
                <p className={`text-brand-dark/40 text-sm ${isRTL ? "mb-5" : "mb-8"}`}>
                  {t.auth.register.sub}
                </p>

                <form onSubmit={submitRegister} className={isRTL ? "space-y-3" : "space-y-4"}>
                  <div className="grid grid-cols-2 gap-3">
                    <Field label={t.auth.register.firstName} icon={<User size={12} weight="bold" />}>
                      <input
                        type="text" required autoComplete="given-name"
                        value={regForm.prenom} placeholder={t.auth.register.firstNamePh}
                        onChange={e => setRegForm(f => ({ ...f, prenom: e.target.value }))}
                        className={inputClass}
                      />
                    </Field>
                    <Field label={t.auth.register.lastName} icon={<User size={12} weight="bold" />}>
                      <input
                        type="text" required autoComplete="family-name"
                        value={regForm.nom} placeholder={t.auth.register.lastNamePh}
                        onChange={e => setRegForm(f => ({ ...f, nom: e.target.value }))}
                        className={inputClass}
                      />
                    </Field>
                  </div>
                  <Field label={t.auth.register.phone} icon={<Phone size={12} weight="bold" />}>
                    <input
                      type="tel" required autoComplete="tel"
                      value={regForm.phone} placeholder="+222 XX XX XX XX"
                      onChange={e => setRegForm(f => ({ ...f, phone: e.target.value }))}
                      className={inputClass}
                    />
                  </Field>
                  <Field label={t.auth.register.email} icon={<EnvelopeSimple size={12} weight="bold" />}>
                    <input
                      type="email" required autoComplete="email"
                      value={regForm.email} placeholder="votre@email.com"
                      onChange={e => setRegForm(f => ({ ...f, email: e.target.value }))}
                      className={inputClass}
                    />
                  </Field>
                  <Field label={t.auth.register.password} icon={<Lock size={12} weight="bold" />}>
                    <input
                      type="password" required autoComplete="new-password"
                      value={regForm.password} placeholder={t.auth.register.passwordPh}
                      onChange={e => setRegForm(f => ({ ...f, password: e.target.value }))}
                      className={inputClass}
                    />
                  </Field>

                  {regError && (
                    <p className="text-red-500 text-sm bg-red-50 border border-red-200 rounded-2xl px-4 py-3">
                      {regError}
                    </p>
                  )}

                  <button
                    type="submit" disabled={regLoading}
                    className="w-full flex items-center justify-center gap-2 bg-brand-dark text-brand-yellow font-bold py-4 rounded-2xl text-sm tracking-wide hover:bg-brand-yellow hover:text-brand-dark disabled:opacity-50 transition-all duration-300 mt-2"
                  >
                    {regLoading ? t.auth.register.loading : t.auth.register.submit}
                    {!regLoading && (isRTL ? <ArrowLeft size={15} weight="bold" /> : <ArrowRight size={15} weight="bold" />)}
                  </button>
                </form>

                <p className="text-center text-brand-dark/60 text-[11px] mt-5 leading-relaxed px-2">
                  En créant un compte, vous acceptez notre{" "}
                  <Link href="/politique-confidentialite" className="text-brand-dark font-semibold underline underline-offset-2 hover:text-brand-dark/60 transition-colors">
                    politique de confidentialité
                  </Link>
                  .
                </p>

                <p className="text-center text-brand-dark/35 text-sm mt-4">
                  {t.auth.register.hasAccount}{" "}
                  <button
                    onClick={() => switchTo("login")}
                    className="text-brand-dark font-bold hover:text-brand-yellow transition-colors"
                  >
                    {t.auth.register.login}
                  </button>
                </p>
              </>
            )}
          </div>
        </div>
      </div>
    </main>
  );
}

function Field({ label, icon, children }: {
  label: string;
  icon: React.ReactNode;
  children: React.ReactNode;
}) {
  return (
    <div>
      <label className="flex items-center gap-1.5 text-brand-dark/45 text-[10px] font-bold tracking-[0.18em] uppercase mb-2">
        {icon} {label}
      </label>
      {children}
    </div>
  );
}
