import React, { useEffect, useState } from 'react';
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, PieChart, Pie, Cell } from 'recharts';
import api from '../hooks/api';
import StatCard from '../components/StatCard';

const COLORS = ['#3b82f6', '#10b981', '#f59e0b', '#ef4444'];

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>;
};

export default function Dashboard() {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    api.get('/api/dashboard').then(r => setData(r.data)).finally(() => setLoading(false));
  }, []);

  if (loading) return <div className="flex justify-center items-center h-64"><div className="animate-spin rounded-full h-10 w-10 border-b-2 border-blue-600"></div></div>;
  if (!data) return <div className="text-center text-red-600 py-10">Failed to load dashboard data</div>;

  const vehiclePie = [
    { name: 'Available', value: Number(data.vehicles?.available) || 0 },
    { name: 'On Trip', value: Number(data.vehicles?.on_trip) || 0 },
    { name: 'Maintenance', value: Number(data.vehicles?.in_maintenance) || 0 },
    { name: 'Inactive', value: Number(data.vehicles?.inactive) || 0 },
  ].filter(x => x.value > 0);

  const fuelChart = (data.fuelByMonth || []).reverse().map(x => ({ month: x.month, Cost: Math.round(x.cost), Liters: Math.round(x.liters) }));

  return (
    <div className="space-y-6">
      <div className="page-header">
        <h1 className="page-title">Dashboard</h1>
        <span className="text-sm text-gray-500">{new Date().toLocaleDateString('en-US', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' })}</span>
      </div>

      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        <StatCard label="Total Vehicles" value={data.vehicles?.total} icon="🚛" color="blue" sub={`${data.vehicles?.available} available`} />
        <StatCard label="Active Drivers" value={data.drivers?.active} icon="👤" color="green" sub={`${data.drivers?.total} total`} />
        <StatCard label="Active Trips" value={data.trips?.active} icon="🗺️" color="yellow" sub={`${data.trips?.completed} completed`} />
        <StatCard label="Revenue" value={`KES ${Number(data.revenue?.paid || 0).toLocaleString()}`} icon="💰" color="purple" sub="Paid invoices" />
      </div>

      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        <StatCard label="Fuel Cost" value={`KES ${Number(data.fuel?.total_cost || 0).toLocaleString()}`} icon="⛽" color="orange" sub={`${Number(data.fuel?.total_liters || 0).toFixed(0)}L total`} />
        <StatCard label="Maintenance" value={data.maintenance?.total} icon="🔧" color="red" sub={`${data.maintenance?.upcoming} upcoming`} />
        <StatCard label="Total Trips" value={data.trips?.total} icon="📦" color="blue" />
        <StatCard label="Outstanding" value={`KES ${Number((data.revenue?.total || 0) - (data.revenue?.paid || 0)).toLocaleString()}`} icon="📄" color="yellow" sub="Unpaid invoices" />
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <div className="card">
          <h3 className="font-semibold text-gray-900 mb-4">Fleet Status</h3>
          {vehiclePie.length > 0 ? (
            <ResponsiveContainer width="100%" height={220}>
              <PieChart>
                <Pie data={vehiclePie} cx="50%" cy="50%" outerRadius={80} dataKey="value" label={({ name, value }) => `${name}: ${value}`}>
                  {vehiclePie.map((_, i) => <Cell key={i} fill={COLORS[i % COLORS.length]} />)}
                </Pie>
                <Tooltip />
              </PieChart>
            </ResponsiveContainer>
          ) : <p className="text-gray-400 text-center py-10">No vehicle data</p>}
        </div>

        <div className="card">
          <h3 className="font-semibold text-gray-900 mb-4">Fuel Consumption (Last 6 Months)</h3>
          {fuelChart.length > 0 ? (
            <ResponsiveContainer width="100%" height={220}>
              <BarChart data={fuelChart}>
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis dataKey="month" tick={{ fontSize: 11 }} />
                <YAxis tick={{ fontSize: 11 }} />
                <Tooltip />
                <Bar dataKey="Cost" fill="#3b82f6" radius={[4,4,0,0]} />
              </BarChart>
            </ResponsiveContainer>
          ) : <p className="text-gray-400 text-center py-10">No fuel data</p>}
        </div>
      </div>

      <div className="card">
        <h3 className="font-semibold text-gray-900 mb-4">Recent Trips</h3>
        <div className="overflow-x-auto">
          <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">Status</th>
              <th className="table-header text-left">Date</th>
            </tr></thead>
            <tbody>
              {(data.recentTrips || []).map(t => (
                <tr key={t.id || t._id} className="table-row">
                  <td className="table-cell font-medium">{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">{statusBadge(t.status)}</td>
                  <td className="table-cell">{new Date(t.scheduled_start).toLocaleDateString()}</td>
                </tr>
              ))}
              {!data.recentTrips?.length && <tr><td colSpan={6} className="text-center py-8 text-gray-400">No trips yet</td></tr>}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}
