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

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

export default function Reports() {
  const [data, setData] = useState(null);
  const [vehicles, setVehicles] = useState([]);
  const [trips, setTrips] = useState([]);
  const [fuel, setFuel] = useState([]);
  const [invoices, setInvoices] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(()=>{
    Promise.all([
      api.get('/api/dashboard'), api.get('/api/vehicles'),
      api.get('/api/trips'), api.get('/api/fuel'), api.get('/api/invoices')
    ]).then(([d,v,t,f,i])=>{
      setData(d.data); setVehicles(v.data); setTrips(t.data); setFuel(f.data); setInvoices(i.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>;

  const statusCount = ['scheduled','in_progress','completed','cancelled'].map(s=>({ name:s.replace('_',' '), value: trips.filter(t=>t.status===s).length }));
  const fuelByVehicle = vehicles.slice(0,5).map(v=>({
    name: v.vehicle_number,
    liters: fuel.filter(f=>(f.vehicle_id===v.id||f.vehicle_id?._id===v._id||f.vehicle_id===v._id)).reduce((s,x)=>s+Number(x.liters||0),0)
  })).filter(x=>x.liters>0);
  const invoiceStatus = ['draft','sent','paid','overdue'].map(s=>({ name:s, value: invoices.filter(i=>i.status===s).length })).filter(x=>x.value>0);
  const fuelChart = (data?.fuelByMonth||[]).slice(0,6).reverse().map(x=>({ month:x.month, Cost:Math.round(x.cost), Liters:Math.round(x.liters) }));

  const print = () => window.print();

  return (
    <div>
      <div className="page-header">
        <h1 className="page-title">Reports & Analytics</h1>
        <button className="btn-secondary" onClick={print}>🖨 Print Report</button>
      </div>

      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
        {[
          ['Total Vehicles', data?.vehicles?.total, '🚛'],
          ['Total Drivers', data?.drivers?.total, '👤'],
          ['Completed Trips', data?.trips?.completed, '✅'],
          ['Total Revenue', `KES ${Number(data?.revenue?.total||0).toLocaleString()}`, '💰'],
        ].map(([l,v,i])=>(
          <div key={l} className="card text-center">
            <div className="text-3xl mb-2">{i}</div>
            <p className="text-2xl font-bold text-gray-900">{v||'0'}</p>
            <p className="text-sm text-gray-500">{l}</p>
          </div>
        ))}
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
        <div className="card">
          <h3 className="font-semibold text-gray-900 mb-4">Trip Status Distribution</h3>
          <ResponsiveContainer width="100%" height={220}>
            <PieChart><Pie data={statusCount} cx="50%" cy="50%" outerRadius={80} dataKey="value" label={({name,value})=>`${name}:${value}`}>
              {statusCount.map((_,i)=><Cell key={i} fill={COLORS[i%COLORS.length]} />)}
            </Pie><Tooltip /></PieChart>
          </ResponsiveContainer>
        </div>
        <div className="card">
          <h3 className="font-semibold text-gray-900 mb-4">Invoice Status</h3>
          <ResponsiveContainer width="100%" height={220}>
            <PieChart><Pie data={invoiceStatus} cx="50%" cy="50%" outerRadius={80} dataKey="value" label={({name,value})=>`${name}:${value}`}>
              {invoiceStatus.map((_,i)=><Cell key={i} fill={COLORS[i%COLORS.length]} />)}
            </Pie><Tooltip /></PieChart>
          </ResponsiveContainer>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
        <div className="card">
          <h3 className="font-semibold text-gray-900 mb-4">Monthly Fuel Cost (KES)</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 className="card">
          <h3 className="font-semibold text-gray-900 mb-4">Top Vehicles by Fuel Consumption</h3>
          {fuelByVehicle.length>0 ? (
            <ResponsiveContainer width="100%" height={220}>
              <BarChart data={fuelByVehicle}><CartesianGrid strokeDasharray="3 3" /><XAxis dataKey="name" tick={{fontSize:11}} /><YAxis tick={{fontSize:11}} /><Tooltip /><Bar dataKey="liters" fill="#10b981" radius={[4,4,0,0]} /></BarChart>
            </ResponsiveContainer>
          ) : <p className="text-gray-400 text-center py-10">No data</p>}
        </div>
      </div>

      <div className="card">
        <h3 className="font-semibold text-gray-900 mb-4">Vehicle Utilization Summary</h3>
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead><tr>
              <th className="table-header text-left">Vehicle</th>
              <th className="table-header text-left">Model</th>
              <th className="table-header text-left">Status</th>
              <th className="table-header text-left">Mileage</th>
              <th className="table-header text-left">Trips</th>
              <th className="table-header text-left">Fuel Spent</th>
            </tr></thead>
            <tbody>
              {vehicles.map(v=>{
                const vTrips = trips.filter(t=>t.vehicle_id===v.id||t.vehicle_id?._id===v._id||t.vehicle_id===v._id);
                const vFuel = fuel.filter(f=>f.vehicle_id===v.id||f.vehicle_id?._id===v._id||f.vehicle_id===v._id);
                const fuelCost = vFuel.reduce((s,x)=>s+Number(x.total_cost||0),0);
                return (
                  <tr key={v.id||v._id} className="table-row">
                    <td className="table-cell font-semibold">{v.vehicle_number}</td>
                    <td className="table-cell">{v.make} {v.model}</td>
                    <td className="table-cell capitalize"><span className={`badge-${v.status==='available'?'success':v.status==='on_trip'?'warning':'danger'}`}>{v.status}</span></td>
                    <td className="table-cell">{Number(v.mileage).toLocaleString()} km</td>
                    <td className="table-cell">{vTrips.length}</td>
                    <td className="table-cell">KES {fuelCost.toLocaleString()}</td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}
