import React, { useEffect, useState } from 'react';
import api from '../hooks/api';
import Modal from '../components/Modal';
import ConfirmDialog from '../components/ConfirmDialog';
import StatCard from '../components/StatCard';

const statusBadge = s => {
  const map = { active: 'badge-success', suspended: 'badge-danger', terminated: 'badge-gray', on_leave: 'badge-warning' };
  return <span className={map[s]||'badge-gray'}>{s?.replace('_',' ')}</span>;
};

const init = { name:'',license_number:'',license_expiry:'',phone:'',email:'',address:'',hire_date:'',date_of_birth:'',emergency_contact:'',emergency_phone:'' };

export default function Drivers() {
  const [drivers, setDrivers] = useState([]);
  const [stats, setStats] = useState({});
  const [loading, setLoading] = useState(true);
  const [modalOpen, setModalOpen] = useState(false);
  const [confirmOpen, setConfirmOpen] = useState(false);
  const [selectedId, setSelectedId] = useState(null);
  const [form, setForm] = useState(init);
  const [editing, setEditing] = useState(false);
  const [search, setSearch] = useState('');

  const fetch = async () => {
    setLoading(true);
    const [d, s] = await Promise.all([api.get('/api/drivers'), api.get('/api/drivers/stats')]);
    setDrivers(d.data); setStats(s.data); setLoading(false);
  };
  useEffect(() => { fetch(); }, []);

  const openAdd = () => { setForm(init); setEditing(false); setModalOpen(true); };
  const openEdit = d => { setForm({...d, license_expiry:d.license_expiry?.slice(0,10), hire_date:d.hire_date?.slice(0,10), date_of_birth:d.date_of_birth?.slice(0,10)||''}); setEditing(true); setSelectedId(d.id||d._id); setModalOpen(true); };

  const handleSubmit = async e => {
    e.preventDefault();
    if (editing) await api.put(`/api/drivers/${selectedId}`, form);
    else await api.post('/api/drivers', form);
    setModalOpen(false); fetch();
  };

  const f = d => d.filter(x => x.name?.toLowerCase().includes(search.toLowerCase()) || x.license_number?.toLowerCase().includes(search.toLowerCase()));

  return (
    <div>
      <div className="page-header">
        <h1 className="page-title">Drivers</h1>
        <button className="btn-primary" onClick={openAdd}>+ Add Driver</button>
      </div>
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
        <StatCard label="Total" value={stats.total} icon="👤" color="blue" />
        <StatCard label="Active" value={stats.active} icon="✅" color="green" />
        <StatCard label="Suspended" value={stats.suspended} icon="🚫" color="red" />
        <StatCard label="On Leave" value={stats.on_leave} icon="🏖️" color="yellow" />
      </div>
      <div className="card">
        <div className="mb-4"><input className="input-field max-w-sm" placeholder="Search drivers..." value={search} onChange={e=>setSearch(e.target.value)} /></div>
        <div className="overflow-x-auto">
          {loading ? <div className="text-center py-10"><div className="animate-spin inline-block rounded-full h-8 w-8 border-b-2 border-blue-600"></div></div> : (
            <table className="w-full">
              <thead><tr>
                <th className="table-header text-left">Name</th>
                <th className="table-header text-left">License</th>
                <th className="table-header text-left">Phone</th>
                <th className="table-header text-left">Status</th>
                <th className="table-header text-left">Hire Date</th>
                <th className="table-header text-left">Trips</th>
                <th className="table-header text-left">Violations</th>
                <th className="table-header text-left">Actions</th>
              </tr></thead>
              <tbody>
                {f(drivers).map(d=>(
                  <tr key={d.id||d._id} className="table-row">
                    <td className="table-cell font-semibold">{d.name}</td>
                    <td className="table-cell">{d.license_number}</td>
                    <td className="table-cell">{d.phone}</td>
                    <td className="table-cell">{statusBadge(d.employment_status)}</td>
                    <td className="table-cell">{d.hire_date?.slice(0,10)}</td>
                    <td className="table-cell">{d.total_trips||0}</td>
                    <td className="table-cell">{d.violations||0}</td>
                    <td className="table-cell">
                      <div className="flex gap-2">
                        <button onClick={()=>openEdit(d)} className="text-blue-600 hover:text-blue-800 text-sm font-medium">Edit</button>
                        <button onClick={()=>{setSelectedId(d.id||d._id);setConfirmOpen(true);}} className="text-red-600 hover:text-red-800 text-sm font-medium">Delete</button>
                      </div>
                    </td>
                  </tr>
                ))}
                {!f(drivers).length && <tr><td colSpan={8} className="text-center py-10 text-gray-400">No drivers found</td></tr>}
              </tbody>
            </table>
          )}
        </div>
      </div>
      <Modal isOpen={modalOpen} onClose={()=>setModalOpen(false)} title={editing?'Edit Driver':'Add Driver'} size="lg">
        <form onSubmit={handleSubmit} className="grid grid-cols-2 gap-4">
          {[['name','Full Name'],['license_number','License Number'],['phone','Phone'],['email','Email'],['address','Address'],['emergency_contact','Emergency Contact'],['emergency_phone','Emergency Phone']].map(([key,label])=>(
            <div key={key} className={key==='address'?'col-span-2':''}>
              <label className="block text-sm font-medium text-gray-700 mb-1">{label}</label>
              <input className="input-field" value={form[key]||''} onChange={e=>setForm({...form,[key]:e.target.value})} required={['name','license_number','phone'].includes(key)} />
            </div>
          ))}
          {[['license_expiry','License Expiry'],['hire_date','Hire Date'],['date_of_birth','Date of Birth']].map(([key,label])=>(
            <div key={key}>
              <label className="block text-sm font-medium text-gray-700 mb-1">{label}</label>
              <input type="date" className="input-field" value={form[key]||''} onChange={e=>setForm({...form,[key]:e.target.value})} required={key!=='date_of_birth'} />
            </div>
          ))}
          {editing && <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Status</label>
            <select className="input-field" value={form.employment_status||'active'} onChange={e=>setForm({...form,employment_status:e.target.value})}>
              {['active','suspended','terminated','on_leave'].map(x=><option key={x}>{x}</option>)}
            </select>
          </div>}
          <div className="col-span-2 flex gap-3 justify-end mt-2">
            <button type="button" className="btn-secondary" onClick={()=>setModalOpen(false)}>Cancel</button>
            <button type="submit" className="btn-primary">{editing?'Update':'Add Driver'}</button>
          </div>
        </form>
      </Modal>
      <ConfirmDialog isOpen={confirmOpen} onClose={()=>setConfirmOpen(false)} onConfirm={async()=>{await api.delete(`/api/drivers/${selectedId}`);fetch();}} />
    </div>
  );
}
