"use client";

import { useState, Suspense } from "react";
import { useSearchParams, useRouter } from "next/navigation";
import Link from "next/link";
import Image from "next/image";
import { Lock, ArrowRight, CheckCircle } from "@phosphor-icons/react";

function ResetPasswordForm() {
  const searchParams = useSearchParams();
  const router       = useRouter();
  const token        = searchParams.get("token") ?? "";

  const [password,  setPassword]  = useState("");
  const [password2, setPassword2] = useState("");
  const [loading,   setLoading]   = useState(false);
  const [done,      setDone]      = useState(false);
  const [error,     setError]     = useState("");

  const submit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError("");
    if (password !== password2) { setError("Les mots de passe ne correspondent pas"); return; }
    setLoading(true);
    try {
      const res  = await fetch("/api/customer/reset-password", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ token, password }),
      });
      const data = await res.json();
      if (!res.ok) { setError(data.error); return; }
      setDone(true);
      setTimeout(() => router.push("/login"), 3000);
    } finally {
      setLoading(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";

  if (!token) return (
    <div className="text-center">
      <p className="text-red-500 text-sm mb-6">Lien invalide.</p>
      <Link href="/forgot-password" className="text-brand-dark font-bold hover:text-brand-yellow transition-colors text-sm">
        Demander un nouveau lien →
      </Link>
    </div>
  );

  return done ? (
    <div className="text-center">
      <CheckCircle size={52} weight="fill" className="text-brand-yellow mx-auto mb-4" />
      <h1 className="text-brand-dark text-2xl font-bold mb-2" style={{ fontFamily: "var(--font-space, sans-serif)" }}>
        Mot de passe mis à jour !
      </h1>
      <p className="text-brand-dark/45 text-sm">Redirection vers la connexion…</p>
    </div>
  ) : (
    <>
      <h1 className="text-brand-dark text-3xl font-bold mb-1" style={{ fontFamily: "var(--font-space, sans-serif)" }}>
        Nouveau mot de passe
      </h1>
      <p className="text-brand-dark/40 text-sm mb-8">Choisissez un mot de passe sécurisé.</p>

      <form onSubmit={submit} className="space-y-4">
        {[
          { label: "Nouveau mot de passe",    val: password,  set: setPassword,  ph: "Minimum 6 caractères" },
          { label: "Confirmer le mot de passe", val: password2, set: setPassword2, ph: "Répétez le mot de passe" },
        ].map(({ label, val, set, ph }) => (
          <div key={label}>
            <label className="flex items-center gap-1.5 text-brand-dark/45 text-[10px] font-bold tracking-[0.18em] uppercase mb-2">
              <Lock size={12} weight="bold" /> {label}
            </label>
            <input
              type="password" required minLength={6}
              value={val} placeholder={ph}
              onChange={e => set(e.target.value)}
              className={inputClass}
            />
          </div>
        ))}

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

        <button
          type="submit" disabled={loading}
          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"
        >
          {loading ? "Enregistrement…" : "Enregistrer"}
          {!loading && <ArrowRight size={15} weight="bold" />}
        </button>
      </form>
    </>
  );
}

export default function ResetPasswordPage() {
  return (
    <main className="min-h-screen flex items-center justify-center bg-brand-off-white px-6 py-16">
      <div className="w-full max-w-sm mx-auto">
        <Link href="/" className="flex justify-center mb-10">
          <Image src="/logo.png" alt="Asli Food" width={80} height={80} className="rounded-2xl" />
        </Link>
        <Suspense>
          <ResetPasswordForm />
        </Suspense>
      </div>
    </main>
  );
}
