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 = { scheduled:'badge-info', in_progress:'badge-warning', completed:'badge-success', cancelled:'badge-gray' };
  return <span className={map[s]||'badge-gray'}>{s?.replace('_',' ')}</span>;
};

const init = { vehicle_id:'', service_type:'routine', service_date:'', next_service_date:'', odometer_at_service:'', service_center:'', technician:'', description:'', parts_replaced:'', cost:'', status:'scheduled', notes:'' };

export default function Maintenance() {
  const [records, setRecords] = useState([]);
  const [stats, setStats] = useState({});
  const [vehicles, setVehicles] = 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 load = async () => {
    setLoading(true);
    const [r,s,v] = await Promise.all([api.get('/api/maintenance'),api.get('/api/maintenance/stats'),api.get('/api/vehicles')]);
    setRecords(r.data); setStats(s.data); setVehicles(v.data); setLoading(false);
  };
  useEffect(()=>{load();},[]);

  const openAdd = () => { setForm({...init, service_date: new Date().toISOString().slice(0,10)}); setEditing(false); setModalOpen(true); };
  const openEdit = r => { setForm({...r, vehicle_id:r.vehicle_id?._id||r.vehicle_id, service_date:r.service_date?.slice(0,10), next_service_date:r.next_service_date?.slice(0,10)||''}); setEditing(true); setSelectedId(r.id||r._id); setModalOpen(true); };

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

  const types = ['routine','repair','inspection','tire','oil_change','brake','engine','other'];

  return (
    <div>
      <div className="page-header">
        <h1 className="page-title">Maintenance</h1>
        <button className="btn-primary" onClick={openAdd}>+ Schedule Maintenance</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="Scheduled" value={stats.scheduled} icon="📅" color="yellow" />
        <StatCard label="In Progress" value={stats.in_progress} icon="⚙️" color="orange" />
        <StatCard label="Total Cost" value={`KES ${Number(stats.total_cost||0).toLocaleString()}`} icon="💰" color="red" />
      </div>
      <div className="card">
        <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">Vehicle</th>
                <th className="table-header text-left">Service Type</th>
                <th className="table-header text-left">Date</th>
                <th className="table-header text-left">Next Service</th>
                <th className="table-header text-left">Center</th>
                <th className="table-header text-left">Cost</th>
                <th className="table-header text-left">Status</th>
                <th className="table-header text-left">Actions</th>
              </tr></thead>
              <tbody>
                {records.map(r=>(
                  <tr key={r.id||r._id} className="table-row">
                    <td className="table-cell font-medium">{r.vehicle_number||r.vehicle_id?.vehicle_number}</td>
                    <td className="table-cell capitalize">{r.service_type?.replace('_',' ')}</td>
                    <td className="table-cell">{r.service_date?.slice(0,10)}</td>
                    <td className="table-cell">{r.next_service_date?.slice(0,10)||'—'}</td>
                    <td className="table-cell">{r.service_center||'—'}</td>
                    <td className="table-cell font-semibold">KES {Number(r.cost).toLocaleString()}</td>
                    <td className="table-cell">{statusBadge(r.status)}</td>
                    <td className="table-cell">
                      <div className="flex gap-2">
                        <button onClick={()=>openEdit(r)} className="text-blue-600 hover:text-blue-800 text-sm font-medium">Edit</button>
                        <button onClick={()=>{setSelectedId(r.id||r._id);setConfirmOpen(true);}} className="text-red-600 hover:text-red-800 text-sm font-medium">Delete</button>
                      </div>
                    </td>
                  </tr>
                ))}
                {!records.length && <tr><td colSpan={8} className="text-center py-10 text-gray-400">No maintenance records</td></tr>}
              </tbody>
            </table>
          )}
        </div>
      </div>
      <Modal isOpen={modalOpen} onClose={()=>setModalOpen(false)} title={editing?'Edit Record':'Schedule Maintenance'} size="lg">
        <form onSubmit={handleSubmit} className="grid grid-cols-2 gap-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Vehicle</label>
            <select className="input-field" value={form.vehicle_id} onChange={e=>setForm({...form,vehicle_id:e.target.value})} required>
              <option value="">-- Select --</option>
              {vehicles.map(v=><option key={v.id||v._id} value={v.id||v._id}>{v.vehicle_number}</option>)}
            </select>
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Service Type</label>
            <select className="input-field" value={form.service_type} onChange={e=>setForm({...form,service_type:e.target.value})}>
              {types.map(x=><option key={x}>{x}</option>)}
            </select>
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Service Date</label>
            <input type="date" className="input-field" value={form.service_date} onChange={e=>setForm({...form,service_date:e.target.value})} required />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Next Service Date</label>
            <input type="date" className="input-field" value={form.next_service_date||''} onChange={e=>setForm({...form,next_service_date:e.target.value})} />
          </div>
          {[['service_center','Service Center'],['technician','Technician'],['cost','Cost (KES)'],['odometer_at_service','Odometer (km)']].map(([k,l])=>(
            <div key={k}>
              <label className="block text-sm font-medium text-gray-700 mb-1">{l}</label>
              <input type={k==='cost'||k==='odometer_at_service'?'number':'text'} className="input-field" value={form[k]||''} onChange={e=>setForm({...form,[k]:e.target.value})} />
            </div>
          ))}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Status</label>
            <select className="input-field" value={form.status} onChange={e=>setForm({...form,status:e.target.value})}>
              {['scheduled','in_progress','completed','cancelled'].map(x=><option key={x}>{x}</option>)}
            </select>
          </div>
          {[['description','Description'],['parts_replaced','Parts Replaced'],['notes','Notes']].map(([k,l])=>(
            <div key={k} className="col-span-2">
              <label className="block text-sm font-medium text-gray-700 mb-1">{l}</label>
              <textarea className="input-field" rows={2} value={form[k]||''} onChange={e=>setForm({...form,[k]:e.target.value})} />
            </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':'Schedule'}</button>
          </div>
        </form>
      </Modal>
      <ConfirmDialog isOpen={confirmOpen} onClose={()=>setConfirmOpen(false)} onConfirm={async()=>{await api.delete(`/api/maintenance/${selectedId}`);load();}} />
    </div>
  );
}
