"use client";

import * as React from "react";
import { useEffect, useMemo, useState } from "react";
import { useSearchParams, useRouter } from "next/navigation";
import { createClient } from "@supabase/supabase-js";
import { Label } from "@/components/ui/label";
import { Separator } from "@/components/ui/separator";
import { Eye, EyeOff, Check, X } from "lucide-react";
import { usePageTitle } from "@/hooks/usePageTitle";

export default function SetPasswordContent() {
  // Définir le titre de la page
  usePageTitle("Définir votre mot de passe");
  
  const router = useRouter();
  const sp = useSearchParams();

  const supabase = useMemo(() => {
    const url = process.env.NEXT_PUBLIC_SUPABASE_URL as string | undefined;
    const key = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY as string | undefined;
    if (!url || !key) return null;
    return createClient(url, key);
  }, []);

  const [checking, setChecking] = useState(true);
  const [exchangeMsg, setExchangeMsg] = useState<string | null>(null);

  // Champs mot de passe
  const [pw1, setPw1] = useState("");
  const [pw2, setPw2] = useState("");
  const [saving, setSaving] = useState(false);
  const [msg, setMsg] = useState<string | null>(null);
  const [done, setDone] = useState(false);

  // Password policy & strength helpers
  const policy = {
    minLen: 12,
    lower: /[a-z]/,
    upper: /[A-Z]/,
    digit: /\d/,
    special: /[^A-Za-z0-9]/,
  };

  function checkPolicy(pw: string) {
    return {
      length: pw.length >= policy.minLen,
      lower: policy.lower.test(pw),
      upper: policy.upper.test(pw),
      digit: policy.digit.test(pw),
      special: policy.special.test(pw),
    };
  }

  function strengthScore(pw: string) {
    if (!pw) return 0;
    const c = checkPolicy(pw);
    let score = 0;
    // Length contribution
    if (pw.length >= 16) score += 2;
    else if (pw.length >= 12) score += 1;
    // Variety contribution
    score += [c.lower, c.upper, c.digit, c.special].filter(Boolean).length - 1; // 0..3
    // Cap between 0..4
    if (score < 0) score = 0; if (score > 4) score = 4;
    return score;
  }

  const s1 = strengthScore(pw1);
  const checks = checkPolicy(pw1);

  const [showPw1, setShowPw1] = useState(false);
  const [showPw2, setShowPw2] = useState(false);

  // 1) À l'arrivée, échanger le code du lien pour obtenir une session
  useEffect(() => {
    let cancelled = false;
    (async () => {
      try {
        if (!supabase) {
          setExchangeMsg("Configuration Supabase manquante.");
          return;
        }
        // Les liens Supabase modernes contiennent ?code=...
        const code = sp.get("code");
        if (code) {
          const { error } = await supabase.auth.exchangeCodeForSession(code);
          if (error) {
            setExchangeMsg(error.message || "Lien invalide ou expiré.");
            return;
          }
        } else {
          // Ancien format (#access_token) : on tente juste de voir s'il y a déjà une session
          const { data } = await supabase.auth.getSession();
          if (!data.session) {
            setExchangeMsg("Lien invalide ou expiré. Veuillez redemander un e-mail.");
            return;
          }
        }
        if (!cancelled) {
          setExchangeMsg(null);
        }
      } catch (e: any) {
        if (!cancelled) setExchangeMsg(e?.message || "Erreur inattendue.");
      } finally {
        if (!cancelled) setChecking(false);
      }
    })();
    return () => {
      cancelled = true;
    };
  }, [sp, supabase]);

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setMsg(null);

    if (!supabase) {
      setMsg("Configuration Supabase manquante.");
      return;
    }
    const c = checkPolicy(pw1);
    if (!c.length || !c.lower || !c.upper || !c.digit || !c.special) {
      setMsg("Le mot de passe doit contenir au moins 12 caractères, avec minuscules, majuscules, chiffres et caractères spéciaux.");
      return;
    }
    if (pw1 !== pw2) {
      setMsg("Les mots de passe ne correspondent pas.");
      return;
    }

    try {
      setSaving(true);
      const { error } = await supabase.auth.updateUser({ password: pw1 });
      if (error) throw error;
      setDone(true);
      setMsg("Mot de passe défini avec succès 🎉");
      setPw1("");
      setPw2("");
    } catch (e: any) {
      setMsg(e?.message || "Échec de la mise à jour.");
    } finally {
      setSaving(false);
    }
  }

  return (
    <div className="max-w-md mx-auto mt-12 p-6 rounded-2xl border bg-white">
      <div className="flex items-center justify-between mb-2">
        <h1 className="text-xl font-semibold">Définir votre mot de passe</h1>
      </div>
      <p className="text-sm text-slate-600 mb-4">
        Ce mot de passe est <strong>facultatif</strong> : vous pourrez toujours vous connecter par code e-mail.
      </p>

      <Separator className="my-4" />

      {checking ? (
        <div className="text-sm text-slate-600">Validation du lien en cours…</div>
      ) : exchangeMsg ? (
        <div className="text-sm text-rose-600">{exchangeMsg}</div>
      ) : done ? (
        <div className="space-y-4">
          <div className="text-sm text-emerald-600">{msg}</div>
          <button
            type="button"
            onClick={() => router.push("/")}
            className="w-full py-2 rounded-lg bg-[var(--brand)] text-slate-900 font-semibold"
          >
            Accéder à l'Espace Paie
          </button>
        </div>
      ) : (
        <form onSubmit={handleSubmit} className="space-y-4">
          <div className="grid gap-2">
            <Label htmlFor="pw1">Nouveau mot de passe</Label>
            <div className="relative">
              <input
                id="pw1"
                type={showPw1 ? "text" : "password"}
                value={pw1}
                onChange={(e) => setPw1(e.target.value)}
                placeholder="Au moins 12 caractères"
                autoComplete="new-password"
                className="w-full px-3 py-2 pr-10 rounded-lg border bg-transparent"
              />
              <button
                type="button"
                onClick={() => setShowPw1(v => !v)}
                aria-label={showPw1 ? "Masquer" : "Afficher"}
                className="absolute inset-y-0 right-2 my-auto h-6 w-6 grid place-items-center text-slate-500 hover:text-slate-700"
              >
                {showPw1 ? <EyeOff className="h-4 w-4"/> : <Eye className="h-4 w-4"/>}
              </button>
            </div>

            {/* Strength meter */}
            <div className="mt-1">
              <div className="flex gap-1">
                {[0,1,2,3].map(i => (
                  <div key={i} className={`h-1 flex-1 rounded-full ${s1>i ? (s1>=3 ? 'bg-emerald-500' : s1===2 ? 'bg-amber-500' : 'bg-rose-500') : 'bg-slate-200'}`}></div>
                ))}
              </div>
              <div className="mt-2 grid grid-cols-2 gap-x-3 gap-y-1 text-xs text-slate-600">
                <div className="flex items-center gap-1">
                  {checks.length ? <Check className="h-3.5 w-3.5 text-emerald-600"/> : <X className="h-3.5 w-3.5 text-rose-500"/>}
                  12 caractères minimum
                </div>
                <div className="flex items-center gap-1">
                  {checks.lower ? <Check className="h-3.5 w-3.5 text-emerald-600"/> : <X className="h-3.5 w-3.5 text-rose-500"/>}
                  1 minuscule (a‑z)
                </div>
                <div className="flex items-center gap-1">
                  {checks.upper ? <Check className="h-3.5 w-3.5 text-emerald-600"/> : <X className="h-3.5 w-3.5 text-rose-500"/>}
                  1 majuscule (A‑Z)
                </div>
                <div className="flex items-center gap-1">
                  {checks.digit ? <Check className="h-3.5 w-3.5 text-emerald-600"/> : <X className="h-3.5 w-3.5 text-rose-500"/>}
                  1 chiffre (0‑9)
                </div>
                <div className="flex items-center gap-1">
                  {checks.special ? <Check className="h-3.5 w-3.5 text-emerald-600"/> : <X className="h-3.5 w-3.5 text-rose-500"/>}
                  1 caractère spécial
                </div>
              </div>
            </div>
          </div>
          <div className="grid gap-2">
            <Label htmlFor="pw2">Confirmer le mot de passe</Label>
            <div className="relative">
              <input
                id="pw2"
                type={showPw2 ? "text" : "password"}
                value={pw2}
                onChange={(e) => setPw2(e.target.value)}
                autoComplete="new-password"
                className="w-full px-3 py-2 pr-10 rounded-lg border bg-transparent"
              />
              <button
                type="button"
                onClick={() => setShowPw2(v => !v)}
                aria-label={showPw2 ? "Masquer" : "Afficher"}
                className="absolute inset-y-0 right-2 my-auto h-6 w-6 grid place-items-center text-slate-500 hover:text-slate-700"
              >
                {showPw2 ? <EyeOff className="h-4 w-4"/> : <Eye className="h-4 w-4"/>}
              </button>
            </div>
          </div>

          {msg && <div className={`text-sm ${msg.includes("succès") || msg.includes("🎉") ? "text-emerald-600" : "text-rose-600"}`}>{msg}</div>}

          <button
            type="submit"
            disabled={saving || !(checks.length && checks.lower && checks.upper && checks.digit && checks.special) || pw1 !== pw2}
            className="w-full py-2 rounded-lg bg-[var(--brand)] text-slate-900 font-semibold disabled:opacity-60"
          >
            {saving ? "Enregistrement…" : "Enregistrer"}
          </button>
        </form>
      )}

      <Separator className="my-4" />
      <div className="text-xs text-slate-500">
        Besoin d'aide ? Vous pouvez redemander un e-mail de définition de mot de passe depuis l'écran de connexion.
      </div>
    </div>
  );
}
