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

const init = { trip_code:'', vehicle_id:'', driver_id:'', customer_id:'', origin:'', destination:'', distance_km:'', scheduled_start:'', scheduled_end:'', cargo_description:'', cargo_weight:'', notes:'', total_cost:'' };

export default function Trips() {
  const [trips, setTrips] = useState([]);
  const [stats, setStats] = useState({});
  const [vehicles, setVehicles] = useState([]);
  const [drivers, setDrivers] = useState([]);
  const [customers, setCustomers] = 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 [t,s,v,d,c] = await Promise.all([
      api.get('/api/trips'), api.get('/api/trips/stats'),
      api.get('/api/vehicles'), api.get('/api/drivers'), api.get('/api/customers')
    ]);
    setTrips(t.data); setStats(s.data); setVehicles(v.data); setDrivers(d.data); setCustomers(c.data); setLoading(false);
  };
  useEffect(()=>{load();},[]);

  const openAdd = () => {
    const code = `TRP-${Date.now().toString().slice(-6)}`;
    setForm({...init, trip_code:code}); setEditing(false); setModalOpen(true);
  };
  const openEdit = t => {
    const vid = t.vehicle_id?._id||t.vehicle_id||'';
    const did = t.driver_id?._id||t.driver_id||'';
    const cid = t.customer_id?._id||t.customer_id||'';
    setForm({...t, vehicle_id:vid, driver_id:did, customer_id:cid, scheduled_start:t.scheduled_start?.slice(0,16), scheduled_end:t.scheduled_end?.slice(0,16)||''});
    setEditing(true); setSelectedId(t.id||t._id); setModalOpen(true);
  };

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

  return (
    <div>
      <div className="page-header">
        <h1 className="page-title">Trips</h1>
        <button className="btn-primary" onClick={openAdd}>+ Add Trip</button>
      </div>
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
        <StatCard label="Total Trips" value={stats.total} icon="🗺️" color="blue" />
        <StatCard label="In Progress" value={stats.in_progress} icon="🚛" color="yellow" />
        <StatCard label="Completed" value={stats.completed} icon="✅" color="green" />
        <StatCard label="Revenue" value={`KES ${Number(stats.total_revenue||0).toLocaleString()}`} icon="💰" color="purple" />
      </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">Code</th>
                <th className="table-header text-left">Route</th>
                <th className="table-header text-left">Driver</th>
                <th className="table-header text-left">Vehicle</th>
                <th className="table-header text-left">Distance</th>
                <th className="table-header text-left">Status</th>
                <th className="table-header text-left">Start</th>
                <th className="table-header text-left">Actions</th>
              </tr></thead>
              <tbody>
                {trips.map(t=>(
                  <tr key={t.id||t._id} className="table-row">
                    <td className="table-cell font-semibold">{t.trip_code}</td>
                    <td className="table-cell">{t.origin} → {t.destination}</td>
                    <td className="table-cell">{t.driver_name||t.driver_id?.name}</td>
                    <td className="table-cell">{t.vehicle_number||t.vehicle_id?.vehicle_number}</td>
                    <td className="table-cell">{t.distance_km?`${t.distance_km} km`:'—'}</td>
                    <td className="table-cell">{statusBadge(t.status)}</td>
                    <td className="table-cell">{t.scheduled_start?.slice(0,10)}</td>
                    <td className="table-cell">
                      <div className="flex gap-2">
                        <button onClick={()=>openEdit(t)} className="text-blue-600 hover:text-blue-800 text-sm font-medium">Edit</button>
                        <button onClick={()=>{setSelectedId(t.id||t._id);setConfirmOpen(true);}} className="text-red-600 hover:text-red-800 text-sm font-medium">Delete</button>
                      </div>
                    </td>
                  </tr>
                ))}
                {!trips.length && <tr><td colSpan={8} className="text-center py-10 text-gray-400">No trips found</td></tr>}
              </tbody>
            </table>
          )}
        </div>
      </div>
      <Modal isOpen={modalOpen} onClose={()=>setModalOpen(false)} title={editing?'Edit Trip':'Add Trip'} 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">Trip Code</label>
            <input className="input-field" value={form.trip_code} onChange={e=>setForm({...form,trip_code:e.target.value})} required />
          </div>
          <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 Vehicle --</option>
              {vehicles.map(v=><option key={v.id||v._id} value={v.id||v._id}>{v.vehicle_number} - {v.model}</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})} required>
              <option value="">-- Select Driver --</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">Customer</label>
            <select className="input-field" value={form.customer_id} onChange={e=>setForm({...form,customer_id:e.target.value})}>
              <option value="">-- None --</option>
              {customers.map(c=><option key={c.id||c._id} value={c.id||c._id}>{c.name}</option>)}
            </select>
          </div>
          {[['origin','Origin'],['destination','Destination']].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})} required />
            </div>
          ))}
          {[['distance_km','Distance (km)'],['cargo_weight','Cargo Weight (kg)'],['total_cost','Total Cost (KES)']].map(([k,l])=>(
            <div key={k}>
              <label className="block text-sm font-medium text-gray-700 mb-1">{l}</label>
              <input type="number" 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">Scheduled Start</label>
            <input type="datetime-local" className="input-field" value={form.scheduled_start||''} onChange={e=>setForm({...form,scheduled_start:e.target.value})} required />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Scheduled End</label>
            <input type="datetime-local" className="input-field" value={form.scheduled_end||''} onChange={e=>setForm({...form,scheduled_end:e.target.value})} />
          </div>
          <div className="col-span-2">
            <label className="block text-sm font-medium text-gray-700 mb-1">Cargo Description</label>
            <textarea className="input-field" rows={2} value={form.cargo_description||''} onChange={e=>setForm({...form,cargo_description:e.target.value})} />
          </div>
          {editing && <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Status</label>
            <select className="input-field" value={form.status||'scheduled'} onChange={e=>setForm({...form,status:e.target.value})}>
              {['scheduled','in_progress','completed','cancelled'].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 Trip'}</button>
          </div>
        </form>
      </Modal>
      <ConfirmDialog isOpen={confirmOpen} onClose={()=>setConfirmOpen(false)} onConfirm={async()=>{await api.delete(`/api/trips/${selectedId}`);load();}} />
    </div>
  );
}
