"use client"

import { useState, useEffect } from "react"
import { useRouter } from "next/navigation"
import { useLocale } from "next-intl"
import { ShieldCheck, Eye, EyeOff, AlertCircle, CheckCircle2, Loader2, Lock } from "lucide-react"

import { changePassword } from "@/src/lib/api/users"
import { useAuth } from "@/src/features/auth/auth-context"
import { tokenStorage } from "@/src/lib/api/storage"

const NAVY = "#1a3578"
const NAVY2 = "#2655b0"
const TEAL = "#4dba96"

const inputClass = `
  w-full rounded-2xl border border-slate-200 bg-white
  px-4 py-3.5 text-[15px] text-slate-900
  placeholder:text-slate-400 outline-none
  transition-all duration-150
  hover:border-slate-300
  disabled:cursor-not-allowed disabled:opacity-50
`

function PasswordStrength({ password }: { password: string }) {
  const checks = [
    { label: "8 caractères minimum", ok: password.length >= 8 },
    { label: "Une lettre majuscule", ok: /[A-Z]/.test(password) },
    { label: "Une lettre minuscule", ok: /[a-z]/.test(password) },
    { label: "Un chiffre", ok: /\d/.test(password) },
  ]
  const score = checks.filter((c) => c.ok).length
  const color = score <= 1 ? "#ef4444" : score === 2 ? "#f97316" : score === 3 ? "#eab308" : TEAL

  return (
    <div className="mt-3 space-y-2">
      {/* Barre de force */}
      <div className="flex gap-1">
        {[1, 2, 3, 4].map((i) => (
          <div
            key={i}
            className="h-1.5 flex-1 rounded-full transition-all duration-300"
            style={{ backgroundColor: i <= score ? color : "#e2e8f0" }}
          />
        ))}
      </div>
      {/* Checklist */}
      <ul className="space-y-1">
        {checks.map((c) => (
          <li key={c.label} className="flex items-center gap-2 text-xs" style={{ color: c.ok ? TEAL : "#94a3b8" }}>
            <CheckCircle2 className="h-3.5 w-3.5 shrink-0" style={{ opacity: c.ok ? 1 : 0.3 }} />
            {c.label}
          </li>
        ))}
      </ul>
    </div>
  )
}

export default function ChangePasswordPage() {
  const router = useRouter()
  const locale = useLocale()
  const { me, refreshMe } = useAuth()

  const [newPwd,     setNewPwd]     = useState("")
  const [confirmPwd, setConfirmPwd] = useState("")
  const [showNew,    setShowNew]    = useState(false)
  const [showConf,   setShowConf]   = useState(false)
  const [loading,    setLoading]    = useState(false)
  const [error,      setError]      = useState<string | null>(null)
  const [success,    setSuccess]    = useState(false)

  // Rediriger si l'utilisateur n'est pas connecté
  useEffect(() => {
    if (!tokenStorage.getAccess()) {
      router.replace(`/${locale}/login`)
    }
  }, [locale, router])

  async function onSubmit(e: React.FormEvent) {
    e.preventDefault()
    setError(null)

    if (newPwd.length < 8) {
      setError("Le mot de passe doit contenir au moins 8 caractères.")
      return
    }
    if (newPwd !== confirmPwd) {
      setError("Les mots de passe ne correspondent pas.")
      return
    }

    setLoading(true)
    try {
      await changePassword(newPwd, confirmPwd)
      setSuccess(true)
      // Actualiser /me pour effacer must_change_password
      await refreshMe()
      // Rediriger après 1.5s
      setTimeout(() => {
        const raw = localStorage.getItem("acx_me")
        const m = raw ? JSON.parse(raw) : null
        if (m?.is_superuser) router.replace(`/${locale}/admin`)
        else router.replace(`/${locale}/dashboard`)
      }, 1500)
    } catch (ex: any) {
      setError(ex?.message ?? "Erreur lors du changement de mot de passe.")
    } finally {
      setLoading(false)
    }
  }

  return (
    <main className="min-h-screen flex items-center justify-center px-4" style={{ background: "#f7f8fc" }}>
      <div className="w-full max-w-[420px]">

        {/* Header */}
        <div className="mb-8 text-center">
          <div
            className="mx-auto mb-5 flex h-14 w-14 items-center justify-center rounded-2xl shadow-md"
            style={{ background: `linear-gradient(135deg, ${NAVY} 0%, ${NAVY2} 100%)` }}
          >
            <Lock className="h-6 w-6 text-white" />
          </div>
          <h1 className="text-2xl font-bold tracking-tight" style={{ color: NAVY }}>
            Changez votre mot de passe
          </h1>
          <p className="mt-2 text-sm leading-relaxed text-slate-500">
            Pour des raisons de sécurité, vous devez définir un nouveau mot de passe avant de continuer.
          </p>
        </div>

        {/* Card */}
        <div className="rounded-3xl border bg-white p-8 shadow-sm">

          {success ? (
            <div className="flex flex-col items-center gap-4 py-4 text-center">
              <div
                className="flex h-12 w-12 items-center justify-center rounded-full"
                style={{ backgroundColor: `${TEAL}22` }}
              >
                <CheckCircle2 className="h-6 w-6" style={{ color: TEAL }} />
              </div>
              <p className="font-semibold text-slate-800">Mot de passe mis à jour</p>
              <p className="text-sm text-slate-400">Redirection en cours…</p>
            </div>
          ) : (
            <form onSubmit={onSubmit} noValidate className="space-y-5">

              {error && (
                <div className="flex items-start gap-3 rounded-2xl border border-red-100 bg-red-50 px-4 py-3 text-sm text-red-700">
                  <AlertCircle className="mt-0.5 h-4 w-4 shrink-0" />
                  <span>{error}</span>
                </div>
              )}

              {/* Nouveau mot de passe */}
              <div className="space-y-2">
                <label className="block text-[11px] font-semibold uppercase tracking-widest text-slate-400">
                  Nouveau mot de passe
                </label>
                <div className="relative">
                  <input
                    type={showNew ? "text" : "password"}
                    value={newPwd}
                    onChange={(e) => setNewPwd(e.target.value)}
                    disabled={loading}
                    placeholder="Minimum 8 caractères"
                    className={`${inputClass} pr-14`}
                    onFocus={(e) => {
                      e.currentTarget.style.borderColor = TEAL
                      e.currentTarget.style.boxShadow = `0 0 0 4px rgba(77,186,150,0.15)`
                    }}
                    onBlur={(e) => {
                      e.currentTarget.style.borderColor = ""
                      e.currentTarget.style.boxShadow = ""
                    }}
                  />
                  <button
                    type="button"
                    tabIndex={-1}
                    onClick={() => setShowNew((v) => !v)}
                    className="absolute right-4 top-1/2 -translate-y-1/2 text-slate-400 transition hover:text-slate-600"
                  >
                    {showNew ? <EyeOff className="h-[18px] w-[18px]" /> : <Eye className="h-[18px] w-[18px]" />}
                  </button>
                </div>
                {newPwd && <PasswordStrength password={newPwd} />}
              </div>

              {/* Confirmation */}
              <div className="space-y-2">
                <label className="block text-[11px] font-semibold uppercase tracking-widest text-slate-400">
                  Confirmer le mot de passe
                </label>
                <div className="relative">
                  <input
                    type={showConf ? "text" : "password"}
                    value={confirmPwd}
                    onChange={(e) => setConfirmPwd(e.target.value)}
                    disabled={loading}
                    placeholder="Répétez le mot de passe"
                    className={`${inputClass} pr-14`}
                    onFocus={(e) => {
                      e.currentTarget.style.borderColor = TEAL
                      e.currentTarget.style.boxShadow = `0 0 0 4px rgba(77,186,150,0.15)`
                    }}
                    onBlur={(e) => {
                      e.currentTarget.style.borderColor = ""
                      e.currentTarget.style.boxShadow = ""
                    }}
                  />
                  <button
                    type="button"
                    tabIndex={-1}
                    onClick={() => setShowConf((v) => !v)}
                    className="absolute right-4 top-1/2 -translate-y-1/2 text-slate-400 transition hover:text-slate-600"
                  >
                    {showConf ? <EyeOff className="h-[18px] w-[18px]" /> : <Eye className="h-[18px] w-[18px]" />}
                  </button>
                </div>
                {/* Indicateur de correspondance */}
                {confirmPwd && (
                  <p
                    className="mt-1 flex items-center gap-1.5 text-xs font-medium"
                    style={{ color: newPwd === confirmPwd ? TEAL : "#ef4444" }}
                  >
                    <CheckCircle2 className="h-3.5 w-3.5" style={{ opacity: newPwd === confirmPwd ? 1 : 0.3 }} />
                    {newPwd === confirmPwd ? "Les mots de passe correspondent" : "Ne correspond pas"}
                  </p>
                )}
              </div>

              {/* Bouton */}
              <button
                type="submit"
                disabled={loading}
                className="mt-2 flex w-full items-center justify-center gap-2.5 rounded-2xl py-3.5 text-[15px] font-semibold text-white transition-all duration-150 active:scale-[0.98] disabled:cursor-not-allowed disabled:opacity-70"
                style={{
                  background: `linear-gradient(135deg, ${NAVY} 0%, ${NAVY2} 100%)`,
                  boxShadow: `0 4px 24px rgba(26,53,120,0.25)`,
                }}
              >
                {loading ? (
                  <>
                    <Loader2 className="h-4 w-4 animate-spin" />
                    Mise à jour…
                  </>
                ) : (
                  <>
                    <ShieldCheck className="h-4 w-4" />
                    Valider le nouveau mot de passe
                  </>
                )}
              </button>
            </form>
          )}
        </div>

        <p className="mt-6 text-center text-[11px] text-slate-300">
          © {new Date().getFullYear()} ACREMAC — Tous droits réservés
        </p>
      </div>
    </main>
  )
}
