import { useState, useEffect, useCallback } from 'react'
import { KeyRound, ArrowLeft, Check, Fingerprint, Plus, Trash2, Key } from 'lucide-react'
import { changePassword, getMyPasskeys, deleteMyPasskey, registerPasskey } from '../api/client'
import { inputClass, PasswordInput } from './ui/controls'

export default function ProfilePage({ username, onBack }) {
  const [oldPassword, setOldPassword] = useState('')
  const [newPassword, setNewPassword] = useState('')
  const [newPassword2, setNewPassword2] = useState('')
  const [error,   setError]   = useState(null)
  const [success, setSuccess] = useState(false)
  const [loading, setLoading] = useState(false)

  // ─── Passkeys ─────────────────────────────────────────────────────────────
  const [passkeys,        setPasskeys]        = useState([])
  const [passkeysLoading, setPasskeysLoading] = useState(true)
  const [passkeysError,   setPasskeysError]   = useState(null)
  const [addName,         setAddName]         = useState('')
  const [adding,          setAdding]          = useState(false)
  const [addError,        setAddError]        = useState(null)
  const [deleteLoading,   setDeleteLoading]   = useState(null)
  const [browserSupports, setBrowserSupports] = useState(false)

  useEffect(() => {
    if (window.PublicKeyCredential) {
      window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()
        .then(ok => setBrowserSupports(ok))
        .catch(() => setBrowserSupports(false))
    }
  }, [])

  const loadPasskeys = useCallback(async () => {
    setPasskeysLoading(true)
    setPasskeysError(null)
    try {
      const data = await getMyPasskeys()
      setPasskeys(data)
    } catch (err) {
      setPasskeysError(err.message)
    } finally {
      setPasskeysLoading(false)
    }
  }, [])

  useEffect(() => { loadPasskeys() }, [loadPasskeys])

  const handleAddPasskey = async (e) => {
    e.preventDefault()
    setAddError(null)
    setAdding(true)
    try {
      const name = addName.trim() || 'Ma passkey'
      await registerPasskey(name)
      setAddName('')
      await loadPasskeys()
    } catch (err) {
      if (err.name === 'NotAllowedError' || err.message?.includes('NotAllowedError')) {
        setAddError('Enregistrement annulé.')
      } else {
        setAddError(err.message)
      }
    } finally {
      setAdding(false)
    }
  }

  const handleDeletePasskey = async (credentialId) => {
    setDeleteLoading(credentialId)
    try {
      await deleteMyPasskey(credentialId)
      setPasskeys(prev => prev.filter(p => p.credential_id !== credentialId))
    } catch (err) {
      setPasskeysError(err.message)
    } finally {
      setDeleteLoading(null)
    }
  }

  // ─── Password change ──────────────────────────────────────────────────────
  const handleSubmit = async (e) => {
    e.preventDefault()
    setError(null)
    setSuccess(false)

    if (newPassword !== newPassword2) {
      setError('Les nouveaux mots de passe ne correspondent pas.')
      return
    }
    if (newPassword.length < 6) {
      setError('Le nouveau mot de passe doit contenir au moins 6 caractères.')
      return
    }

    setLoading(true)
    try {
      await changePassword(oldPassword, newPassword)
      setSuccess(true)
      setOldPassword('')
      setNewPassword('')
      setNewPassword2('')
    } catch (err) {
      setError(err.message)
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="min-h-screen bg-gray-950 text-gray-100">
      <div className="max-w-lg mx-auto px-4 py-10">
        <button
          onClick={onBack}
          className="flex items-center gap-1.5 text-sm text-gray-400 hover:text-gray-200 mb-6 transition-colors"
        >
          <ArrowLeft size={15} />
          Retour au tableau de bord
        </button>

        <div className="flex items-center gap-3 mb-6">
          <div className="p-2 rounded-xl bg-indigo-500/15">
            <KeyRound size={20} className="text-indigo-400" />
          </div>
          <div>
            <h1 className="text-lg font-semibold">Mon profil</h1>
            <p className="text-xs text-gray-500">{username}</p>
          </div>
        </div>

        <div className="bg-gray-900 border border-gray-800 rounded-2xl p-6">
          <h2 className="text-sm font-medium text-gray-300 mb-4">Changer le mot de passe</h2>

          {success && (
            <div className="flex items-center gap-2 bg-emerald-950/40 border border-emerald-800/50 rounded-lg px-3 py-2 text-xs text-emerald-300 mb-4">
              <Check size={13} />
              Mot de passe mis à jour avec succès.
            </div>
          )}

          {error && (
            <div role="alert" className="bg-red-950/40 border border-red-800/50 rounded-lg px-3 py-2 text-xs text-red-300 mb-4">
              {error}
            </div>
          )}

          <form onSubmit={handleSubmit} className="space-y-4">
            <div>
              <label htmlFor="current-password" className="block text-xs text-gray-400 mb-1.5">Mot de passe actuel</label>
              <PasswordInput
                id="current-password"
                required
                autoComplete="current-password"
                value={oldPassword}
                onChange={(e) => setOldPassword(e.target.value)}
              />
            </div>

            <div>
              <label htmlFor="new-password" className="block text-xs text-gray-400 mb-1.5">Nouveau mot de passe</label>
              <PasswordInput
                id="new-password"
                required
                autoComplete="new-password"
                value={newPassword}
                onChange={(e) => setNewPassword(e.target.value)}
              />
            </div>

            <div>
              <label htmlFor="new-password-2" className="block text-xs text-gray-400 mb-1.5">Confirmer le nouveau mot de passe</label>
              <PasswordInput
                id="new-password-2"
                required
                autoComplete="new-password"
                value={newPassword2}
                onChange={(e) => setNewPassword2(e.target.value)}
              />
            </div>

            <button
              type="submit"
              disabled={loading}
              className="w-full py-2 rounded-lg bg-indigo-600 hover:bg-indigo-500 disabled:opacity-50 text-sm font-medium transition-colors mt-2"
            >
              {loading ? 'Enregistrement…' : 'Changer le mot de passe'}
            </button>
          </form>
        </div>

        {/* ── Passkeys ── */}
        {browserSupports && (
          <div className="bg-gray-900 border border-gray-800 rounded-2xl p-6 mt-6">
            <div className="flex items-center gap-2 mb-1">
              <Fingerprint size={15} className="text-indigo-400" />
              <h2 className="text-sm font-medium text-gray-300">Passkeys (TouchID / FaceID)</h2>
            </div>
            <p className="text-xs text-gray-500 mb-4">
              Connectez-vous sans mot de passe grâce à la biométrie de votre appareil.
            </p>

            {passkeysError && (
              <div className="bg-red-950/40 border border-red-800/50 rounded-lg px-3 py-2 text-xs text-red-300 mb-3">
                {passkeysError}
              </div>
            )}

            {/* Liste des passkeys */}
            {passkeysLoading
              ? <p className="text-xs text-gray-500 mb-4">Chargement…</p>
              : passkeys.length === 0
                ? <p className="text-xs text-gray-500 mb-4">Aucune passkey enregistrée.</p>
                : (
                  <ul className="divide-y divide-gray-800 mb-4">
                    {passkeys.map(pk => (
                      <li key={pk.credential_id} className="flex items-center justify-between gap-3 py-2.5">
                        <div className="flex items-center gap-2 min-w-0">
                          <Key size={13} className="text-indigo-400 flex-shrink-0" />
                          <div className="min-w-0">
                            <p className="text-sm text-gray-200 truncate">{pk.name}</p>
                            <p className="text-xs text-gray-500">
                              {new Date(pk.created_at).toLocaleDateString('fr-FR')}
                            </p>
                          </div>
                        </div>
                        <button
                          onClick={() => handleDeletePasskey(pk.credential_id)}
                          disabled={deleteLoading === pk.credential_id}
                          className="flex items-center gap-1 px-2.5 py-1.5 rounded-lg text-xs text-red-400 hover:bg-red-950/40 disabled:opacity-50 transition-colors flex-shrink-0"
                        >
                          <Trash2 size={11} />
                          {deleteLoading === pk.credential_id ? '…' : 'Supprimer'}
                        </button>
                      </li>
                    ))}
                  </ul>
                )
            }

            {/* Formulaire d'ajout */}
            {addError && (
              <div className="bg-red-950/40 border border-red-800/50 rounded-lg px-3 py-2 text-xs text-red-300 mb-3">
                {addError}
              </div>
            )}
            <form onSubmit={handleAddPasskey} className="flex gap-2">
              <input
                type="text"
                placeholder="Nom de l'appareil (ex : MacBook)"
                aria-label="Nom de l'appareil pour la nouvelle passkey"
                value={addName}
                onChange={e => setAddName(e.target.value)}
                disabled={adding}
                className={`${inputClass} flex-1`}
              />
              <button
                type="submit"
                disabled={adding}
                className="flex items-center gap-1.5 px-3 py-2 rounded-lg bg-indigo-600 hover:bg-indigo-500 disabled:opacity-50 text-sm font-medium transition-colors flex-shrink-0"
              >
                <Plus size={14} />
                {adding ? 'En cours…' : 'Ajouter'}
              </button>
            </form>
          </div>
        )}

      </div>
    </div>
  )
}
