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 init = { vehicle_id:'', driver_id:'', trip_id:'', fuel_date:'', liters:'', cost_per_liter:'', total_cost:'', station_name:'', station_location:'', odometer_reading:'', fuel_type:'diesel', receipt_number:'', notes:'' };

export default function Fuel() {
  const [logs, setLogs] = useState([]);
  const [stats, setStats] = useState({});
  const [vehicles, setVehicles] = useState([]);
  const [drivers, setDrivers] = 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 [l,s,v,d] = await Promise.all([api.get('/api/fuel'),api.get('/api/fuel/stats'),api.get('/api/vehicles'),api.get('/api/drivers')]);
    setLogs(l.data); setStats(s.data); setVehicles(v.data); setDrivers(d.data); setLoading(false);
  };
  useEffect(()=>{load();},[]);

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

  const calcTotal = (liters, cost_per_liter) => {
    const t = (parseFloat(liters)||0) * (parseFloat(cost_per_liter)||0);
    return t.toFixed(2);
  };

  const handleSubmit = async e => {
    e.preventDefault();
    const payload = {...form, total_cost: form.total_cost || calcTotal(form.liters, form.cost_per_liter)};
    if (editing) await api.put(`/api/fuel/${selectedId}`, payload);
    else await api.post('/api/fuel', payload);
    setModalOpen(false); load();
  };

  return (
    <div>
      <div className="page-header">
        <h1 className="page-title">Fuel Management</h1>
        <button className="btn-primary" onClick={openAdd}>+ Add Fuel Log</button>
      </div>
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
        <StatCard label="Total Records" value={stats.total_records} icon="⛽" color="blue" />
        <StatCard label="Total Liters" value={`${Number(stats.total_liters||0).toFixed(0)}L`} icon="🛢️" color="yellow" />
        <StatCard label="Total Cost" value={`KES ${Number(stats.total_cost||0).toLocaleString()}`} icon="💰" color="red" />
        <StatCard label="Avg Per Fill" value={`${Number(stats.avg_liters||0).toFixed(1)}L`} icon="📊" color="green" />
      </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">Driver</th>
                <th className="table-header text-left">Date</th>
                <th className="table-header text-left">Liters</th>
                <th className="table-header text-left">Cost/L</th>
                <th className="table-header text-left">Total</th>
                <th className="table-header text-left">Station</th>
                <th className="table-header text-left">Odometer</th>
                <th className="table-header text-left">Actions</th>
              </tr></thead>
              <tbody>
                {logs.map(l=>(
                  <tr key={l.id||l._id} className="table-row">
                    <td className="table-cell font-medium">{l.vehicle_number||l.vehicle_id?.vehicle_number}</td>
                    <td className="table-cell">{l.driver_name||l.driver_id?.name||'—'}</td>
                    <td className="table-cell">{l.fuel_date?.slice(0,10)}</td>
                    <td className="table-cell">{l.liters}L</td>
                    <td className="table-cell">KES {l.cost_per_liter}</td>
                    <td className="table-cell font-semibold">KES {Number(l.total_cost).toLocaleString()}</td>
                    <td className="table-cell">{l.station_name||'—'}</td>
                    <td className="table-cell">{Number(l.odometer_reading).toLocaleString()} km</td>
                    <td className="table-cell">
                      <div className="flex gap-2">
                        <button onClick={()=>openEdit(l)} className="text-blue-600 hover:text-blue-800 text-sm font-medium">Edit</button>
                        <button onClick={()=>{setSelectedId(l.id||l._id);setConfirmOpen(true);}} className="text-red-600 hover:text-red-800 text-sm font-medium">Delete</button>
                      </div>
                    </td>
                  </tr>
                ))}
                {!logs.length && <tr><td colSpan={9} className="text-center py-10 text-gray-400">No fuel logs</td></tr>}
              </tbody>
            </table>
          )}
        </div>
      </div>
      <Modal isOpen={modalOpen} onClose={()=>setModalOpen(false)} title={editing?'Edit Fuel Log':'Add Fuel Log'} 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">Driver</label>
            <select className="input-field" value={form.driver_id} onChange={e=>setForm({...form,driver_id:e.target.value})}>
              <option value="">-- None --</option>
              {drivers.map(d=><option key={d.id||d._id} value={d.id||d._id}>{d.name}</option>)}
            </select>
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Date</label>
            <input type="date" className="input-field" value={form.fuel_date} onChange={e=>setForm({...form,fuel_date: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} onChange={e=>setForm({...form,fuel_type:e.target.value})}>
              {['petrol','diesel','electric_charge','other'].map(x=><option key={x}>{x}</option>)}
            </select>
          </div>
          {[['liters','Liters'],['cost_per_liter','Cost per Liter (KES)'],['odometer_reading','Odometer (km)']].map(([k,l])=>(
            <div key={k}>
              <label className="block text-sm font-medium text-gray-700 mb-1">{l}</label>
              <input type="number" step="0.01" className="input-field" value={form[k]||''} onChange={e=>{
                const upd = {...form,[k]:e.target.value};
                if(k==='liters'||k==='cost_per_liter') upd.total_cost = calcTotal(upd.liters, upd.cost_per_liter);
                setForm(upd);
              }} required={k!=='odometer_reading'||k==='odometer_reading'} />
            </div>
          ))}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Total Cost (KES)</label>
            <input type="number" step="0.01" className="input-field bg-gray-50" value={form.total_cost||''} onChange={e=>setForm({...form,total_cost:e.target.value})} />
          </div>
          {[['station_name','Station Name'],['station_location','Station Location'],['receipt_number','Receipt Number']].map(([k,l])=>(
            <div key={k}>
              <label className="block text-sm font-medium text-gray-700 mb-1">{l}</label>
              <input className="input-field" 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':'Add Log'}</button>
          </div>
        </form>
      </Modal>
      <ConfirmDialog isOpen={confirmOpen} onClose={()=>setConfirmOpen(false)} onConfirm={async()=>{await api.delete(`/api/fuel/${selectedId}`);load();}} />
    </div>
  );
}
