import React, { useMemo } from 'react';
import { fmt } from '@/lib/fleetData';
import { TrendingUp, TrendingDown, Receipt, Download } from 'lucide-react';
import { useFleetData } from '@/contexts/FleetDataContext';

const COST_PER_MILE = 1.85; // fuel + maintenance + driver pay estimate
const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

const invColor: Record<string, string> = {
  Paid: 'bg-emerald-100 text-emerald-700', Sent: 'bg-blue-100 text-blue-700',
  Overdue: 'bg-red-100 text-red-700', Draft: 'bg-slate-100 text-slate-600',
};

const FinancialsView: React.FC = () => {
  const { drivers, invoices, loads } = useFleetData();

  // Build monthly revenue/expense buckets from real load data.
  const { monthly, totalRev, totalExp } = useMemo(() => {
    const buckets: Record<number, { rev: number; exp: number }> = {};
    loads.forEach((l) => {
      const d = new Date(l.pickupDate);
      const m = isNaN(d.getTime()) ? new Date().getMonth() : d.getMonth();
      if (!buckets[m]) buckets[m] = { rev: 0, exp: 0 };
      buckets[m].rev += l.rate || 0;
      buckets[m].exp += ((l.miles || 0) + (l.deadhead || 0)) * COST_PER_MILE;
    });
    // Show the 6 most recent months that have data, or fall back to last 6 calendar months.
    const monthsWithData = Object.keys(buckets).map(Number).sort((a, b) => a - b);
    const keys = monthsWithData.length ? monthsWithData.slice(-6) : [];
    const monthly = keys.map((m) => ({ m: MONTHS[m], rev: Math.round(buckets[m].rev), exp: Math.round(buckets[m].exp) }));
    const totalRev = loads.reduce((s, l) => s + (l.rate || 0), 0);
    const totalExp = Math.round(loads.reduce((s, l) => s + ((l.miles || 0) + (l.deadhead || 0)) * COST_PER_MILE, 0));
    return { monthly, totalRev, totalExp };
  }, [loads]);

  const profit = totalRev - totalExp;
  const maxBar = Math.max(1, ...monthly.map((m) => Math.max(m.rev, m.exp)));
  const profitPerMile = useMemo(() => {
    const totalMiles = loads.reduce((s, l) => s + (l.miles || 0), 0);
    return totalMiles > 0 ? (profit / totalMiles).toFixed(2) : '0.00';
  }, [loads, profit]);
  const maxDriverRev = Math.max(1, ...drivers.map((d) => d.revenueThisWeek || 0));

  return (
    <div className="space-y-6">
      <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
        <div className="bg-white rounded-xl border border-slate-200 p-5">
          <p className="text-xs text-slate-500">Booked Revenue</p><p className="text-2xl font-bold text-slate-900 mt-1">{fmt(totalRev)}</p>
          <p className="flex items-center gap-1 text-xs text-[#00C853] font-medium mt-1"><TrendingUp className="w-3.5 h-3.5" /> {loads.length} loads tracked</p>
        </div>
        <div className="bg-white rounded-xl border border-slate-200 p-5">
          <p className="text-xs text-slate-500">Est. Operating Cost</p><p className="text-2xl font-bold text-slate-900 mt-1">{fmt(totalExp)}</p>
          <p className="flex items-center gap-1 text-xs text-[#FF9800] font-medium mt-1"><TrendingDown className="w-3.5 h-3.5" /> ${COST_PER_MILE.toFixed(2)} / mile basis</p>
        </div>
        <div className="bg-[#0B3D91] rounded-xl p-5 text-white">
          <p className="text-xs text-blue-200">Net Margin</p><p className="text-2xl font-bold mt-1">{fmt(profit)}</p>
          <p className="text-xs text-[#00C853] font-medium mt-1">${profitPerMile} profit / mile</p>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <div className="bg-white rounded-xl border border-slate-200 p-5">
          <h2 className="font-semibold text-slate-900 mb-1">Revenue vs Expenses</h2><p className="text-xs text-slate-500 mb-5">By pickup month · derived from live loads</p>
          {monthly.length === 0 ? (
            <div className="h-48 flex items-center justify-center text-sm text-slate-400">No load data yet.</div>
          ) : (
            <div className="flex items-end justify-between gap-3 h-48">
              {monthly.map((m) => (
                <div key={m.m} className="flex-1 flex flex-col items-center gap-1.5">
                  <div className="w-full flex items-end justify-center gap-1 h-40">
                    <div className="w-1/2 bg-[#0B3D91] rounded-t" style={{ height: `${(m.rev / maxBar) * 100}%` }} title={fmt(m.rev)} />
                    <div className="w-1/2 bg-[#FF9800] rounded-t" style={{ height: `${(m.exp / maxBar) * 100}%` }} title={fmt(m.exp)} />
                  </div>
                  <span className="text-[11px] text-slate-500">{m.m}</span>
                </div>
              ))}
            </div>
          )}
          <div className="flex gap-4 mt-3 text-[11px] text-slate-500">
            <span className="flex items-center gap-1"><i className="w-2.5 h-2.5 bg-[#0B3D91] inline-block rounded" /> Revenue</span>
            <span className="flex items-center gap-1"><i className="w-2.5 h-2.5 bg-[#FF9800] inline-block rounded" /> Expenses</span>
          </div>
        </div>
        <div className="bg-white rounded-xl border border-slate-200 p-5">
          <h2 className="font-semibold text-slate-900 mb-1">Revenue by Driver</h2><p className="text-xs text-slate-500 mb-5">This week's settlements</p>
          <div className="space-y-3">
            {drivers.slice(0, 6).map((d) => {
              const pct = ((d.revenueThisWeek || 0) / maxDriverRev) * 100;
              return (
                <div key={d.id}>
                  <div className="flex justify-between text-xs mb-1"><span className="text-slate-600">{d.name}</span><span className="font-semibold text-slate-900">${(d.revenueThisWeek || 0).toLocaleString()}</span></div>
                  <div className="h-2 bg-slate-100 rounded-full overflow-hidden"><div className="h-full bg-[#00C853] rounded-full" style={{ width: `${pct}%` }} /></div>
                </div>
              );
            })}
            {drivers.length === 0 && <p className="text-sm text-slate-400">No drivers yet.</p>}
          </div>
        </div>
      </div>

      <div className="bg-white rounded-xl border border-slate-200">
        <div className="flex items-center justify-between px-5 py-4 border-b border-slate-100">
          <h2 className="font-semibold text-slate-900">Invoices</h2>
          <button className="flex items-center gap-1 text-xs font-medium text-[#0B3D91] hover:underline"><Download className="w-4 h-4" /> Export QuickBooks</button>
        </div>
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead><tr className="bg-slate-50 text-left text-xs uppercase text-slate-500">
              <th className="px-5 py-3 font-semibold">Invoice #</th><th className="px-5 py-3 font-semibold">Broker</th>
              <th className="px-5 py-3 font-semibold hidden sm:table-cell">Load</th><th className="px-5 py-3 font-semibold text-right">Amount</th>
              <th className="px-5 py-3 font-semibold">Status</th><th className="px-5 py-3 font-semibold hidden md:table-cell">Due</th><th className="px-5 py-3"></th>
            </tr></thead>
            <tbody className="divide-y divide-slate-100">
              {invoices.map((iv) => (
                <tr key={iv.id} className="hover:bg-slate-50">
                  <td className="px-5 py-3 font-mono text-xs font-bold text-[#0B3D91]">{iv.invoiceNumber}</td>
                  <td className="px-5 py-3 font-medium text-slate-800">{iv.broker}</td>
                  <td className="px-5 py-3 text-slate-600 hidden sm:table-cell">{iv.loadNumber}</td>
                  <td className="px-5 py-3 text-right font-semibold text-slate-900">{fmt(iv.amount)}</td>
                  <td className="px-5 py-3"><span className={`text-[11px] font-medium px-2 py-0.5 rounded-full ${invColor[iv.status]}`}>{iv.status}</span></td>
                  <td className="px-5 py-3 text-slate-600 hidden md:table-cell">{iv.dueDate}</td>
                  <td className="px-5 py-3 text-right"><button className="text-slate-400 hover:text-[#0B3D91]"><Receipt className="w-4 h-4" /></button></td>
                </tr>
              ))}
              {invoices.length === 0 && <tr><td colSpan={7} className="px-5 py-8 text-center text-slate-400">No invoices yet.</td></tr>}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
};
export default FinancialsView;
