import { useEffect, useState } from 'react'
import { Link } from 'react-router-dom'
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 overflow-y-auto">
      <div className="bg-white rounded-2xl shadow-xl w-full max-w-lg my-4">
        <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 = { property_id: '', tenant_id: '', start_date: '', end_date: '', rent_amount: '', charges_amount: '', deposit_amount: '', payment_day: '1' }

export default function Leases() {
  const [leases, setLeases] = useState([])
  const [properties, setProperties] = useState([])
  const [tenants, setTenants] = useState([])
  const [showModal, setShowModal] = useState(false)
  const [form, setForm] = useState(emptyForm)
  const [loading, setLoading] = useState(false)

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

  const handleSubmit = async e => {
    e.preventDefault(); setLoading(true)
    try {
      await api.post('/leases', { ...form, property_id: Number(form.property_id), tenant_id: Number(form.tenant_id) })
      toast.success('Bail créé !')
      setShowModal(false); load()
    } catch (err) { toast.error(err.response?.data?.error || 'Erreur') }
    finally { setLoading(false) }
  }

  const handleToggle = async lease => {
    try {
      await api.put(`/leases/${lease.id}`, {
        end_date: lease.end_date, rent_amount: lease.rent_amount, charges_amount: lease.charges_amount,
        deposit_amount: lease.deposit_amount, payment_day: lease.payment_day, active: lease.active ? 0 : 1
      })
      toast.success(lease.active ? 'Bail clôturé' : 'Bail réactivé'); load()
    } catch { toast.error('Erreur') }
  }

  const fmt = v => `${Number(v).toFixed(2)} €`
  const fmtDate = d => d ? new Date(d).toLocaleDateString('fr-FR') : '—'

  return (
    <div>
      <div className="flex items-center justify-between mb-8">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">📋 Baux</h1>
          <p className="text-gray-500 mt-1">{leases.filter(l => l.active).length} bail(s) actif(s)</p>
        </div>
        <button onClick={() => { setForm(emptyForm); setShowModal(true) }} className="btn-primary">+ Nouveau bail</button>
      </div>

      {leases.length === 0 ? (
        <div className="card text-center py-16">
          <div className="text-5xl mb-4">📋</div>
          <p className="text-gray-500">Aucun bail. Commencez par ajouter vos biens et locataires.</p>
        </div>
      ) : (
        <div className="space-y-3">
          {leases.map(l => (
            <div key={l.id} className={`card hover:shadow-md transition-shadow ${!l.active ? 'opacity-60' : ''}`}>
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-4">
                  <div>
                    <div className="flex items-center gap-2">
                      <h3 className="font-semibold text-gray-900">{l.tenant_first_name} {l.tenant_last_name}</h3>
                      <span className={l.active ? 'badge-green' : 'badge-red'}>{l.active ? 'Actif' : 'Clôturé'}</span>
                    </div>
                    <p className="text-sm text-gray-500">{l.property_name} · {l.property_address}, {l.property_city}</p>
                    <p className="text-sm text-gray-400">Du {fmtDate(l.start_date)}{l.end_date ? ` au ${fmtDate(l.end_date)}` : ''}</p>
                  </div>
                </div>
                <div className="flex items-center gap-6">
                  <div className="text-right">
                    <p className="font-semibold text-gray-900">{fmt(l.rent_amount + l.charges_amount)}/mois</p>
                    <p className="text-xs text-gray-400">Loyer {fmt(l.rent_amount)} + Charges {fmt(l.charges_amount)}</p>
                  </div>
                  <div className="flex gap-2">
                    <Link to={`/leases/${l.id}`} className="btn-secondary text-sm px-3 py-1.5">Détail</Link>
                    <button onClick={() => handleToggle(l)} className={`text-sm px-3 py-1.5 rounded-lg transition-colors ${l.active ? 'bg-red-50 text-red-600 hover:bg-red-100' : 'bg-green-50 text-green-600 hover:bg-green-100'}`}>
                      {l.active ? 'Clôturer' : 'Réactiver'}
                    </button>
                  </div>
                </div>
              </div>
            </div>
          ))}
        </div>
      )}

      {showModal && (
        <Modal title="Nouveau bail" onClose={() => setShowModal(false)}>
          <form onSubmit={handleSubmit} className="space-y-4">
            <div>
              <label className="label">Bien *</label>
              <select className="input" required value={form.property_id} onChange={e => setForm(f => ({ ...f, property_id: e.target.value }))}>
                <option value="">Sélectionner un bien</option>
                {properties.map(p => <option key={p.id} value={p.id}>{p.name} — {p.city}</option>)}
              </select>
            </div>
            <div>
              <label className="label">Locataire *</label>
              <select className="input" required value={form.tenant_id} onChange={e => setForm(f => ({ ...f, tenant_id: e.target.value }))}>
                <option value="">Sélectionner un locataire</option>
                {tenants.map(t => <option key={t.id} value={t.id}>{t.first_name} {t.last_name}</option>)}
              </select>
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="label">Date de début *</label>
                <input className="input" type="date" required value={form.start_date} onChange={e => setForm(f => ({ ...f, start_date: e.target.value }))} />
              </div>
              <div>
                <label className="label">Date de fin</label>
                <input className="input" type="date" value={form.end_date} onChange={e => setForm(f => ({ ...f, end_date: e.target.value }))} />
              </div>
              <div>
                <label className="label">Loyer HC (€) *</label>
                <input className="input" type="number" step="0.01" min="0" required value={form.rent_amount} onChange={e => setForm(f => ({ ...f, rent_amount: e.target.value }))} placeholder="800" />
              </div>
              <div>
                <label className="label">Charges (€)</label>
                <input className="input" type="number" step="0.01" min="0" value={form.charges_amount} onChange={e => setForm(f => ({ ...f, charges_amount: e.target.value }))} placeholder="80" />
              </div>
              <div>
                <label className="label">Dépôt de garantie (€)</label>
                <input className="input" type="number" step="0.01" min="0" value={form.deposit_amount} onChange={e => setForm(f => ({ ...f, deposit_amount: e.target.value }))} placeholder="1600" />
              </div>
              <div>
                <label className="label">Jour de paiement</label>
                <input className="input" type="number" min="1" max="28" value={form.payment_day} onChange={e => setForm(f => ({ ...f, payment_day: e.target.value }))} placeholder="1" />
              </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 ? '...' : 'Créer le bail'}</button>
            </div>
          </form>
        </Modal>
      )}
    </div>
  )
}
