import { useEffect, useState } from 'react'
import api from '../api'
import toast from 'react-hot-toast'

function Modal({ title, onClose, children }) {
  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
      <div className="bg-white rounded-2xl shadow-xl w-full max-w-lg">
        <div className="flex items-center justify-between p-6 border-b">
          <h2 className="text-lg font-semibold">{title}</h2>
          <button onClick={onClose} className="text-gray-400 hover:text-gray-600 text-2xl leading-none">&times;</button>
        </div>
        <div className="p-6">{children}</div>
      </div>
    </div>
  )
}

const emptyForm = { first_name: '', last_name: '', email: '', phone: '' }

export default function Tenants() {
  const [tenants, setTenants] = useState([])
  const [showModal, setShowModal] = useState(false)
  const [form, setForm] = useState(emptyForm)
  const [editing, setEditing] = useState(null)
  const [loading, setLoading] = useState(false)

  const load = () => api.get('/tenants').then(r => setTenants(r.data))
  useEffect(() => { load() }, [])

  const openAdd = () => { setForm(emptyForm); setEditing(null); setShowModal(true) }
  const openEdit = t => {
    setForm({ first_name: t.first_name, last_name: t.last_name, email: t.email || '', phone: t.phone || '' })
    setEditing(t.id); setShowModal(true)
  }

  const handleSubmit = async e => {
    e.preventDefault(); setLoading(true)
    try {
      if (editing) await api.put(`/tenants/${editing}`, form)
      else await api.post('/tenants', form)
      toast.success(editing ? 'Locataire modifié !' : 'Locataire ajouté !')
      setShowModal(false); load()
    } catch (err) { toast.error(err.response?.data?.error || 'Erreur') }
    finally { setLoading(false) }
  }

  const handleDelete = async id => {
    if (!confirm('Supprimer ce locataire ?')) return
    try { await api.delete(`/tenants/${id}`); toast.success('Locataire supprimé'); load() }
    catch (err) { toast.error(err.response?.data?.error || 'Erreur') }
  }

  return (
    <div>
      <div className="flex items-center justify-between mb-8">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">👤 Locataires</h1>
          <p className="text-gray-500 mt-1">{tenants.length} locataire(s) enregistré(s)</p>
        </div>
        <button onClick={openAdd} className="btn-primary">+ Ajouter un locataire</button>
      </div>

      {tenants.length === 0 ? (
        <div className="card text-center py-16">
          <div className="text-5xl mb-4">👤</div>
          <p className="text-gray-500">Aucun locataire enregistré.</p>
        </div>
      ) : (
        <div className="card overflow-hidden p-0">
          <table className="w-full">
            <thead className="bg-gray-50 border-b">
              <tr>
                <th className="text-left px-6 py-3 text-sm font-semibold text-gray-600">Nom</th>
                <th className="text-left px-6 py-3 text-sm font-semibold text-gray-600">Email</th>
                <th className="text-left px-6 py-3 text-sm font-semibold text-gray-600">Téléphone</th>
                <th className="px-6 py-3"></th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-50">
              {tenants.map(t => (
                <tr key={t.id} className="hover:bg-gray-50">
                  <td className="px-6 py-4 font-medium text-gray-900">{t.first_name} {t.last_name}</td>
                  <td className="px-6 py-4 text-gray-600">{t.email || '—'}</td>
                  <td className="px-6 py-4 text-gray-600">{t.phone || '—'}</td>
                  <td className="px-6 py-4 text-right space-x-3">
                    <button onClick={() => openEdit(t)} className="text-gray-400 hover:text-blue-600">✏️</button>
                    <button onClick={() => handleDelete(t.id)} className="text-gray-400 hover:text-red-600">🗑️</button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {showModal && (
        <Modal title={editing ? 'Modifier le locataire' : 'Ajouter un locataire'} onClose={() => setShowModal(false)}>
          <form onSubmit={handleSubmit} className="space-y-4">
            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="label">Prénom *</label>
                <input className="input" required value={form.first_name} onChange={e => setForm(f => ({ ...f, first_name: e.target.value }))} />
              </div>
              <div>
                <label className="label">Nom *</label>
                <input className="input" required value={form.last_name} onChange={e => setForm(f => ({ ...f, last_name: e.target.value }))} />
              </div>
              <div className="col-span-2">
                <label className="label">Email</label>
                <input className="input" type="email" value={form.email} onChange={e => setForm(f => ({ ...f, email: e.target.value }))} />
              </div>
              <div className="col-span-2">
                <label className="label">Téléphone</label>
                <input className="input" value={form.phone} onChange={e => setForm(f => ({ ...f, phone: e.target.value }))} />
              </div>
            </div>
            <div className="flex gap-3 pt-2">
              <button type="button" onClick={() => setShowModal(false)} className="btn-secondary flex-1">Annuler</button>
              <button type="submit" disabled={loading} className="btn-primary flex-1">{loading ? '...' : 'Enregistrer'}</button>
            </div>
          </form>
        </Modal>
      )}
    </div>
  )
}
