"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { CheckCircle2, Eye, EyeOff, Loader2 } from "lucide-react";

export function RegisterForm() {
  const router = useRouter();
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [showPwd, setShowPwd] = useState(false);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [done, setDone] = useState(false);

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setError(null);
    setLoading(true);

    try {
      const res = await fetch("/api/auth/register", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ name, email, password }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error ?? "Erreur lors de l'inscription");
      if (data.emailError) {
        console.warn("[register] email error:", data.emailError);
        throw new Error(`Compte créé mais l'email de confirmation n'a pas pu être envoyé : ${data.emailError}`);
      }
      setDone(true);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Erreur inconnue");
    } finally {
      setLoading(false);
    }
  }

  if (done) {
    return (
      <div className="rounded-2xl border border-slate-200 bg-white p-8 shadow-sm text-center">
        <CheckCircle2 className="mx-auto mb-4 h-12 w-12 text-teal-600" />
        <h2 className="text-xl font-bold text-slate-900">Vérifiez vos emails !</h2>
        <p className="mt-3 text-sm text-slate-600 leading-relaxed">
          Un email de confirmation a été envoyé à <strong>{email}</strong>.<br />
          Cliquez sur le lien pour activer votre compte.
        </p>
        <p className="mt-4 text-xs text-slate-400">
          Pas reçu ?{" "}
          <button
            type="button"
            onClick={() => { setDone(false); setEmail(""); }}
            className="text-teal-700 underline"
          >
            Réessayer
          </button>
        </p>
      </div>
    );
  }

  return (
    <div className="rounded-2xl border border-slate-200 bg-white p-8 shadow-sm">
      <form onSubmit={handleSubmit} className="space-y-4">
        <div>
          <label className="mb-1.5 block text-sm font-medium text-slate-700">
            Prénom et nom
          </label>
          <input
            type="text"
            autoComplete="name"
            value={name}
            onChange={(e) => setName(e.target.value)}
            required
            minLength={2}
            className="w-full rounded-lg border border-slate-300 px-3 py-2.5 outline-none focus:border-teal-500 focus:ring-2 focus:ring-teal-200"
            placeholder="Jean Dupont"
          />
        </div>

        <div>
          <label className="mb-1.5 block text-sm font-medium text-slate-700">Email</label>
          <input
            type="email"
            autoComplete="email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            required
            className="w-full rounded-lg border border-slate-300 px-3 py-2.5 outline-none focus:border-teal-500 focus:ring-2 focus:ring-teal-200"
            placeholder="vous@exemple.fr"
          />
        </div>

        <div>
          <label className="mb-1.5 block text-sm font-medium text-slate-700">
            Mot de passe{" "}
            <span className="font-normal text-slate-400">(8 car. min)</span>
          </label>
          <div className="relative">
            <input
              type={showPwd ? "text" : "password"}
              autoComplete="new-password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              required
              minLength={8}
              className="w-full rounded-lg border border-slate-300 px-3 py-2.5 pr-10 outline-none focus:border-teal-500 focus:ring-2 focus:ring-teal-200"
              placeholder="••••••••"
            />
            <button
              type="button"
              onClick={() => setShowPwd((v) => !v)}
              className="absolute right-3 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600"
            >
              {showPwd ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
            </button>
          </div>
        </div>

        {error && (
          <div className="rounded-lg border border-rose-300 bg-rose-50 px-3 py-2 text-sm text-rose-800">
            {error}
          </div>
        )}

        <button
          type="submit"
          disabled={loading}
          className="flex w-full items-center justify-center gap-2 rounded-lg bg-teal-600 py-2.5 text-sm font-semibold text-white hover:bg-teal-700 disabled:opacity-60"
        >
          {loading && <Loader2 className="h-4 w-4 animate-spin" />}
          Créer mon compte
        </button>

        <p className="text-center text-xs text-slate-400 leading-relaxed">
          En vous inscrivant, vous acceptez nos{" "}
          <Link href="/legal" className="underline">CGU</Link>
          {" "}et notre{" "}
          <Link href="/legal" className="underline">politique de confidentialité</Link>.
        </p>
      </form>

      <p className="mt-6 text-center text-sm text-slate-500">
        Déjà inscrit ?{" "}
        <Link href="/auth/login" className="font-medium text-teal-700 hover:underline">
          Se connecter
        </Link>
      </p>
    </div>
  );
}
