import { useEffect, useState } from 'react'
import { api } from '../api/client'
import type { AdminStats, User } from '../api/types'

export function Admin() {
  const [users, setUsers] = useState<User[]>([])
  const [stats, setStats] = useState<AdminStats | null>(null)
  const [loading, setLoading] = useState(true)
  const [currentPw, setCurrentPw] = useState('')
  const [newPw, setNewPw] = useState('')
  const [confirmPw, setConfirmPw] = useState('')
  const [pwMsg, setPwMsg] = useState<string | null>(null)
  const [pwErr, setPwErr] = useState<string | null>(null)
  const [resetPwUserId, setResetPwUserId] = useState<number | null>(null)
  const [resetPwValue, setResetPwValue] = useState('')
  const [resetPwConfirm, setResetPwConfirm] = useState('')
  const [resetPwError, setResetPwError] = useState<string | null>(null)
  const [resetPwSuccess, setResetPwSuccess] = useState<number | null>(null)

  useEffect(() => {
    Promise.all([api.adminListUsers(), api.adminStats()])
      .then(([u, s]) => { setUsers(u); setStats(s) })
      .finally(() => setLoading(false))
  }, [])

  const handleDelete = async (userId: number, username: string) => {
    if (!confirm(`Supprimer l'utilisateur "${username}" et toutes ses données ?`)) return
    await api.adminDeleteUser(userId)
    setUsers((prev) => prev.filter((u) => u.id !== userId))
    setStats((prev) => prev ? { ...prev, users: prev.users - 1 } : prev)
  }

  const handleToggleAdmin = async (userId: number, currentIsAdmin: boolean) => {
    const user = users.find((u) => u.id === userId)
    const action = currentIsAdmin ? 'rétrograder' : 'promouvoir'
    if (!confirm(`Voulez-vous ${action} "${user?.username}" ${currentIsAdmin ? 'en utilisateur normal' : 'en admin'} ?`)) return
    await api.adminToggleAdmin(userId, !currentIsAdmin)
    setUsers((prev) => prev.map((u) => u.id === userId ? { ...u, is_admin: !currentIsAdmin } : u))
  }

  const handleResetPassword = async (userId: number) => {
    setResetPwError(null)
    setResetPwSuccess(null)
    if (resetPwValue !== resetPwConfirm) {
      setResetPwError('Les mots de passe ne correspondent pas')
      return
    }
    try {
      await api.adminResetPassword(userId, resetPwValue)
      setResetPwSuccess(userId)
      setResetPwValue('')
      setResetPwConfirm('')
      setResetPwUserId(null)
      setTimeout(() => setResetPwSuccess(null), 3000)
    } catch (err) {
      setResetPwError(err instanceof Error ? err.message : 'Erreur')
    }
  }

  const handleChangePassword = async (e: React.FormEvent) => {
    e.preventDefault()
    setPwMsg(null)
    setPwErr(null)
    if (newPw !== confirmPw) {
      setPwErr('Les mots de passe ne correspondent pas')
      return
    }
    try {
      await api.changePassword(currentPw, newPw)
      setPwMsg('Mot de passe modifié !')
      setCurrentPw('')
      setNewPw('')
      setConfirmPw('')
    } catch (err) {
      setPwErr(err instanceof Error ? err.message : 'Erreur')
    }
  }

  if (loading) {
    return (
      <div className="max-w-3xl mx-auto space-y-4 animate-pulse">
        <div className="h-8 bg-cellar-card rounded w-1/3" />
        <div className="h-24 bg-cellar-card rounded" />
        <div className="h-48 bg-cellar-card rounded" />
      </div>
    )
  }

  return (
    <div className="max-w-3xl mx-auto space-y-6">
      <h2 className="font-display text-3xl font-bold text-cellar-cream">
        Administration
      </h2>

      {stats && (
        <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
          <StatCard label="Utilisateurs" value={stats.users} icon="👤" />
          <StatCard label="Boissons" value={stats.drinks} icon="🍷" />
          <StatCard label="Invitations" value={stats.invitations} icon="📨" />
          <StatCard label="Utilisées" value={stats.invitations_used} icon="✅" />
        </div>
      )}

      <div>
        <h3 className="text-lg font-semibold text-cellar-cream mb-3">
          Utilisateurs ({users.length})
        </h3>

        <div className="space-y-2">
          {users.map((user) => (
            <div key={user.id} className="card p-4 space-y-3">
              <div className="flex items-center justify-between gap-4">
                <div className="min-w-0">
                  <div className="flex items-center gap-2">
                    <span className="font-medium text-cellar-cream">{user.username}</span>
                    {user.is_admin && (
                      <span className="text-xs bg-cellar-gold/20 text-cellar-gold px-2 py-0.5 rounded-full border border-cellar-gold/30">
                        Admin
                      </span>
                    )}
                  </div>
                  <p className="text-sm text-cellar-muted truncate">{user.email}</p>
                  <p className="text-xs text-cellar-muted">
                    Inscrit le {new Date(user.created_at).toLocaleDateString('fr-FR')}
                  </p>
                </div>

                <div className="flex items-center gap-1 shrink-0">
                  <button
                    onClick={() => handleToggleAdmin(user.id, user.is_admin)}
                    className="text-cellar-gold hover:text-cellar-gold/80 hover:bg-cellar-gold/10 px-2 py-1.5 rounded-lg text-sm transition-colors"
                    title={user.is_admin ? 'Rétrograder en utilisateur' : 'Promouvoir admin'}
                  >
                    {user.is_admin ? '👑' : '👤'}
                  </button>
                  <button
                    onClick={() => { setResetPwUserId(resetPwUserId === user.id ? null : user.id); setResetPwError(null); setResetPwValue(''); setResetPwConfirm(''); }}
                    className="text-blue-400 hover:text-blue-300 hover:bg-blue-900/20 px-2 py-1.5 rounded-lg text-sm transition-colors"
                    title="Changer le mot de passe"
                  >
                    🔑
                  </button>
                  {!user.is_admin && (
                    <button
                      onClick={() => handleDelete(user.id, user.username)}
                      className="text-red-400 hover:text-red-300 hover:bg-red-900/20 px-2 py-1.5 rounded-lg text-sm transition-colors"
                      title="Supprimer"
                    >
                      🗑️
                    </button>
                  )}
                </div>
              </div>

              {resetPwUserId === user.id && (
                <form onSubmit={(e) => { e.preventDefault(); handleResetPassword(user.id) }} className="space-y-2 bg-cellar-dark/50 rounded-lg p-3">
                  <p className="text-sm text-cellar-muted">Nouveau mot de passe pour <strong className="text-cellar-cream">{user.username}</strong></p>
                  {resetPwError && <div className="bg-red-900/30 border border-red-800 text-red-300 px-3 py-2 rounded-lg text-sm">{resetPwError}</div>}
                  {resetPwSuccess === user.id && <div className="bg-green-900/30 border border-green-800 text-green-300 px-3 py-2 rounded-lg text-sm">Mot de passe modifié !</div>}
                  <input
                    type="password"
                    value={resetPwValue}
                    onChange={(e) => setResetPwValue(e.target.value)}
                    placeholder="Nouveau mot de passe"
                    className="input-field"
                    required
                    minLength={8}
                    autoFocus
                    autoComplete="new-password"
                  />
                  <input
                    type="password"
                    value={resetPwConfirm}
                    onChange={(e) => setResetPwConfirm(e.target.value)}
                    placeholder="Confirmer le mot de passe"
                    className="input-field"
                    required
                    minLength={8}
                    autoComplete="new-password"
                  />
                  <div className="flex gap-2">
                    <button type="submit" className="btn-primary text-sm">Confirmer</button>
                    <button type="button" onClick={() => setResetPwUserId(null)} className="text-cellar-muted hover:text-cellar-cream text-sm">Annuler</button>
                  </div>
                </form>
              )}
            </div>
          ))}
        </div>
      </div>

      <div className="card p-4">
        <h3 className="text-lg font-semibold text-cellar-cream mb-3">
          Changer le mot de passe
        </h3>
        <form onSubmit={handleChangePassword} className="space-y-3">
          {pwMsg && <div className="bg-green-900/30 border border-green-800 text-green-300 px-3 py-2 rounded-lg text-sm">{pwMsg}</div>}
          {pwErr && <div className="bg-red-900/30 border border-red-800 text-red-300 px-3 py-2 rounded-lg text-sm">{pwErr}</div>}
          <input
            type="password"
            value={currentPw}
            onChange={(e) => setCurrentPw(e.target.value)}
            placeholder="Mot de passe actuel"
            className="input-field"
            required
            autoComplete="current-password"
          />
          <input
            type="password"
            value={newPw}
            onChange={(e) => setNewPw(e.target.value)}
            placeholder="Nouveau mot de passe"
            className="input-field"
            required
            minLength={8}
            autoComplete="new-password"
          />
          <input
            type="password"
            value={confirmPw}
            onChange={(e) => setConfirmPw(e.target.value)}
            placeholder="Confirmer le mot de passe"
            className="input-field"
            required
            minLength={8}
            autoComplete="new-password"
          />
          <button type="submit" className="btn-primary">
            Modifier
          </button>
        </form>
      </div>
    </div>
  )
}

function StatCard({ label, value, icon }: { label: string; value: number; icon: string }) {
  return (
    <div className="card p-4 text-center">
      <div className="text-2xl mb-1">{icon}</div>
      <div className="text-2xl font-bold text-cellar-gold">{value}</div>
      <div className="text-xs text-cellar-muted">{label}</div>
    </div>
  )
}
