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 = { available: 'badge-success', on_trip: 'badge-warning', maintenance: 'badge-danger', inactive: 'badge-gray' };
  return <span className={map[s] || 'badge-gray'}>{s?.replace('_', ' ')}</span>;
};

const initForm = { vehicle_number: '', model: '', make: '', year: new Date().getFullYear(), registration_number: '', insurance_expiry: '', capacity: '', fuel_type: 'diesel', purchase_date: '', mileage: 0, color: '', vin: '' };

export default function Vehicles() {
  const [vehicles, setVehicles] = 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(initForm);
  const [editing, setEditing] = useState(false);
  const [search, setSearch] = useState('');

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

  useEffect(() => { fetch(); }, []);

  const openAdd = () => { setForm(initForm); setEditing(false); setModalOpen(true); };
  const openEdit = v => { setForm({ ...v, insurance_expiry: v.insurance_expiry?.slice(0,10), purchase_date: v.purchase_date?.slice(0,10) }); setEditing(true); setSelectedId(v.id || v._id); setModalOpen(true); };
  const handleDelete = id => { setSelectedId(id); setConfirmOpen(true); };

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

  const f = v => v.filter(x => x.vehicle_number?.toLowerCase().includes(search.toLowerCase()) || x.model?.toLowerCase().includes(search.toLowerCase()) || x.registration_number?.toLowerCase().includes(search.toLowerCase()));

  return (
    <div>
      <div className="page-header">
        <h1 className="page-title">Vehicles</h1>
        <button className="btn-primary" onClick={openAdd}>+ Add Vehicle</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="Available" value={stats.available} icon="✅" color="green" />
        <StatCard label="On Trip" value={stats.on_trip} icon="🗺️" color="yellow" />
        <StatCard label="Maintenance" value={stats.maintenance} icon="🔧" color="red" />
      </div>

      <div className="card">
        <div className="mb-4">
          <input className="input-field max-w-sm" placeholder="Search vehicles..." 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">Number</th>
                <th className="table-header text-left">Make/Model</th>
                <th className="table-header text-left">Registration</th>
                <th className="table-header text-left">Status</th>
                <th className="table-header text-left">Capacity</th>
                <th className="table-header text-left">Mileage</th>
                <th className="table-header text-left">Ins. Expiry</th>
                <th className="table-header text-left">Actions</th>
              </tr></thead>
              <tbody>
                {f(vehicles).map(v => (
                  <tr key={v.id || v._id} className="table-row">
                    <td className="table-cell font-semibold">{v.vehicle_number}</td>
                    <td className="table-cell">{v.year} {v.make} {v.model}</td>
                    <td className="table-cell">{v.registration_number}</td>
                    <td className="table-cell">{statusBadge(v.status)}</td>
                    <td className="table-cell">{Number(v.capacity).toLocaleString()} kg</td>
                    <td className="table-cell">{Number(v.mileage).toLocaleString()} km</td>
                    <td className="table-cell">{v.insurance_expiry?.slice(0,10)}</td>
                    <td className="table-cell">
                      <div className="flex gap-2">
                        <button onClick={() => openEdit(v)} className="text-blue-600 hover:text-blue-800 text-sm font-medium">Edit</button>
                        <button onClick={() => handleDelete(v.id || v._id)} className="text-red-600 hover:text-red-800 text-sm font-medium">Delete</button>
                      </div>
                    </td>
                  </tr>
                ))}
                {!f(vehicles).length && <tr><td colSpan={8} className="text-center py-10 text-gray-400">No vehicles found</td></tr>}
              </tbody>
            </table>
          )}
        </div>
      </div>

      <Modal isOpen={modalOpen} onClose={() => setModalOpen(false)} title={editing ? 'Edit Vehicle' : 'Add Vehicle'} size="lg">
        <form onSubmit={handleSubmit} className="grid grid-cols-2 gap-4">
          {[['vehicle_number','Vehicle Number'],['model','Model'],['make','Make'],['year','Year'],['registration_number','Reg. Number'],['color','Color'],['vin','VIN'],['capacity','Capacity (kg)'],['mileage','Mileage (km)']].map(([key,label]) => (
            <div key={key}>
              <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={['vehicle_number','model','make','year','registration_number','capacity'].includes(key)} />
            </div>
          ))}
          {[['insurance_expiry','Insurance Expiry','date'],['purchase_date','Purchase Date','date']].map(([key,label,type]) => (
            <div key={key}>
              <label className="block text-sm font-medium text-gray-700 mb-1">{label}</label>
              <input type={type} className="input-field" value={form[key]||''} onChange={e=>setForm({...form,[key]:e.target.value})} required />
            </div>
          ))}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Fuel Type</label>
            <select className="input-field" value={form.fuel_type||'diesel'} onChange={e=>setForm({...form,fuel_type:e.target.value})}>
              {['petrol','diesel','electric','hybrid'].map(x=><option key={x}>{x}</option>)}
            </select>
          </div>
          {editing && <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Status</label>
            <select className="input-field" value={form.status||'available'} onChange={e=>setForm({...form,status:e.target.value})}>
              {['available','on_trip','maintenance','inactive'].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 Vehicle'}</button>
          </div>
        </form>
      </Modal>

      <ConfirmDialog isOpen={confirmOpen} onClose={() => setConfirmOpen(false)} onConfirm={async () => { await api.delete(`/api/vehicles/${selectedId}`); fetch(); }} />
    </div>
  );
}
