"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, LogOut } from "lucide-react"

import { customerPortalApi } from "@/src/lib/api/customer-portal-client"
import { customerPortalTokenStorage } from "@/src/lib/api/customer-portal-storage"
import { customerPortalLogout } from "@/src/lib/api/customer-portal-auth"

const TEAL      = "#3aaa87"
const TEAL_MID  = "#2d9073"
const TEAL_DEEP = "#1f7560"

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">
      <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>
      <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 ClientChangePasswordPage() {
  const router = useRouter()
  const locale = useLocale()

  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 pas de token portail
  useEffect(() => {
    if (!customerPortalTokenStorage.getAccess()) {
      router.replace(`/${locale}/client/login`)
    }
  }, [locale, router])

  function onLogout() {
    customerPortalLogout()
    router.replace(`/${locale}/client/login`)
  }

  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 {
      // Appel via le client portail (utilise le token portail)
      await customerPortalApi.request("/users/change-password/", {
        method: "POST",
        body: JSON.stringify({ new_password: newPwd, confirm_password: confirmPwd }),
      })
      setSuccess(true)
      // On efface les tokens : le JWT actuel a encore must_change_password=true
      // L'utilisateur doit se reconnecter pour obtenir un token propre
      customerPortalLogout()
      setTimeout(() => {
        router.replace(`/${locale}/client/login?reason=password_changed`)
      }, 1800)
    } 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: `linear-gradient(160deg, ${TEAL_DEEP}11 0%, #f5fbf8 40%, #ffffff 100%)` }}>
      <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, ${TEAL_DEEP} 0%, ${TEAL_MID} 60%, ${TEAL} 100%)` }}>
            <Lock className="h-6 w-6 text-white" />
          </div>
          <div className="inline-flex items-center gap-2 rounded-full px-3 py-1 mb-4 text-xs font-semibold"
            style={{ background: "rgba(58,170,135,0.12)", color: TEAL_DEEP }}>
            <ShieldCheck className="h-3.5 w-3.5" />
            Sécurité du compte
          </div>
          <h1 className="text-2xl font-bold tracking-tight" style={{ color: TEAL_DEEP }}>
            Définissez votre mot de passe
          </h1>
          <p className="mt-2 text-sm leading-relaxed text-slate-500 max-w-sm mx-auto">
            Pour des raisons de sécurité, vous devez définir un nouveau mot de passe personnel avant d'accéder au portail.
          </p>
        </div>

        {/* Card */}
        <div className="rounded-3xl border bg-white p-8 shadow-sm" style={{ borderColor: "rgba(58,170,135,0.15)" }}>

          {success ? (
            <div className="flex flex-col items-center gap-4 py-4 text-center">
              <div className="flex h-14 w-14 items-center justify-center rounded-full"
                style={{ backgroundColor: `${TEAL}22` }}>
                <CheckCircle2 className="h-7 w-7" style={{ color: TEAL }} />
              </div>
              <div>
                <p className="font-bold text-slate-800 text-lg">Mot de passe défini !</p>
                <p className="text-sm text-slate-400 mt-1">Reconnectez-vous avec votre nouveau mot de passe…</p>
              </div>
            </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(58,170,135,0.14)`
                    }}
                    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(58,170,135,0.14)`
                    }}
                    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>
                {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, ${TEAL_DEEP} 0%, ${TEAL_MID} 60%, ${TEAL} 100%)`,
                  boxShadow: `0 4px 24px rgba(45,144,115,0.28)`,
                }}>
                {loading ? (
                  <><Loader2 className="h-4 w-4 animate-spin" /> Mise à jour…</>
                ) : (
                  <><ShieldCheck className="h-4 w-4" /> Valider le mot de passe</>
                )}
              </button>
            </form>
          )}
        </div>

        {/* Logout link */}
        {!success && (
          <div className="mt-5 text-center">
            <button onClick={onLogout}
              className="inline-flex items-center gap-1.5 text-[13px] text-slate-400 hover:text-slate-600 transition">
              <LogOut className="h-3.5 w-3.5" />
              Se déconnecter
            </button>
          </div>
        )}

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