'use client'
import { useState, useEffect } from 'react'

interface User {
  id: string
  email: string
  name: string
  role: string
  createdAt: string
}

interface FormData {
  email: string
  name: string
  password: string
  role: 'admin' | 'gestionnaire'
}

const EMPTY_FORM: FormData = { email: '', name: '', password: '', role: 'gestionnaire' }

export function UsersManager() {
  const [users, setUsers] = useState<User[]>([])
  const [loading, setLoading] = useState(true)
  const [form, setForm] = useState<FormData>(EMPTY_FORM)
  const [submitting, setSubmitting] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [success, setSuccess] = useState<string | null>(null)

  const load = () => {
    setLoading(true)
    fetch('/api/admin/users')
      .then((r) => r.json())
      .then(setUsers)
      .catch(() => setError('Impossible de charger les utilisateurs'))
      .finally(() => setLoading(false))
  }

  useEffect(load, [])

  const handleCreate = async (e: React.FormEvent) => {
    e.preventDefault()
    setSubmitting(true)
    setError(null)
    setSuccess(null)
    try {
      const res = await fetch('/api/admin/users', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(form),
      })
      const data = await res.json()
      if (!res.ok) throw new Error(data.error)
      setSuccess(`Utilisateur ${data.name} créé.`)
      setForm(EMPTY_FORM)
      load()
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Erreur')
    } finally {
      setSubmitting(false)
    }
  }

  const handleDelete = async (id: string, name: string) => {
    if (!confirm(`Supprimer ${name} ?`)) return
    try {
      const res = await fetch(`/api/admin/users/${id}`, { method: 'DELETE' })
      const data = await res.json()
      if (!res.ok) throw new Error(data.error)
      load()
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Erreur suppression')
    }
  }

  return (
    <div className="bg-slate-800 rounded-xl p-6">
      <h2 className="text-lg font-semibold text-white mb-4">Gestion des utilisateurs</h2>

      {/* Liste */}
      {loading ? (
        <p className="text-gray-400 text-sm mb-6">Chargement…</p>
      ) : (
        <div className="mb-6 space-y-2">
          {users.map((u) => (
            <div key={u.id} className="flex items-center justify-between p-3 bg-slate-700 rounded-lg">
              <div>
                <p className="text-sm font-medium text-white">{u.name}</p>
                <p className="text-xs text-gray-400">{u.email} — <span className="capitalize">{u.role}</span></p>
              </div>
              <button
                onClick={() => handleDelete(u.id, u.name)}
                className="text-red-400 hover:text-red-300 text-xs px-2 py-1 rounded hover:bg-red-900/30 transition-colors"
              >
                Supprimer
              </button>
            </div>
          ))}
          {users.length === 0 && <p className="text-gray-400 text-sm">Aucun utilisateur.</p>}
        </div>
      )}

      {/* Formulaire création */}
      <form onSubmit={handleCreate} className="space-y-3">
        <h3 className="text-sm font-medium text-gray-300">Nouvel utilisateur</h3>
        <div className="grid grid-cols-2 gap-3">
          <input
            required
            type="email"
            placeholder="Email"
            value={form.email}
            onChange={(e) => setForm((f) => ({ ...f, email: e.target.value }))}
            className="bg-slate-700 border border-slate-600 rounded-lg px-3 py-2 text-sm text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-indigo-500"
          />
          <input
            required
            type="text"
            placeholder="Nom"
            value={form.name}
            onChange={(e) => setForm((f) => ({ ...f, name: e.target.value }))}
            className="bg-slate-700 border border-slate-600 rounded-lg px-3 py-2 text-sm text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-indigo-500"
          />
          <input
            required
            type="password"
            placeholder="Mot de passe"
            value={form.password}
            onChange={(e) => setForm((f) => ({ ...f, password: e.target.value }))}
            className="bg-slate-700 border border-slate-600 rounded-lg px-3 py-2 text-sm text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-indigo-500"
          />
          <select
            value={form.role}
            onChange={(e) => setForm((f) => ({ ...f, role: e.target.value as FormData['role'] }))}
            className="bg-slate-700 border border-slate-600 rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:ring-2 focus:ring-indigo-500"
          >
            <option value="gestionnaire">Gestionnaire</option>
            <option value="admin">Admin</option>
          </select>
        </div>
        {error && <p className="text-red-400 text-sm">{error}</p>}
        {success && <p className="text-green-400 text-sm">{success}</p>}
        <button
          type="submit"
          disabled={submitting}
          className="px-4 py-2 bg-indigo-600 hover:bg-indigo-700 disabled:opacity-50 text-white rounded-lg text-sm font-medium transition-colors"
        >
          {submitting ? 'Création…' : "Créer l'utilisateur"}
        </button>
      </form>
    </div>
  )
}
