/**
 * @license
 * SPDX-License-Identifier: Apache-2.0
 */

/**
 * Delivery Reports — replicated from the operations console (nearle_console/
 * reports), rebuilt against the shared console UI kit (`./consoleUi`) so it
 * matches the source design (gradient header, KPI cards, pill tabs, status-chip /
 * metric-pill tables, gradient total bars, gradient export button). Three report
 * tabs map onto the live Fiesta endpoints: Orders Summary (getlocationsummary),
 * Riders Summary (getfleetsummary), Orders Details (getdeliveries + CSV). The
 * map-based reports need a mapping stack / GPS telemetry → "awaiting backend".
 */

import React, { useMemo, useState } from 'react';
import { TrendingUp, Clock, CheckCircle2, IndianRupee, Bike, Truck, Calendar, Store } from 'lucide-react';
import { useFiestaLocationSummary, useFiestaFleetSummary, useFiestaOrderSummary, useFiestaAllOrders, useFiestaRevenueSummary } from '../services/fiestaQueries';
import { ResponsiveContainer, AreaChart, Area, BarChart, Bar, PieChart, Pie, Cell, XAxis, YAxis, Tooltip as RechartsTooltip, CartesianGrid, Legend } from 'recharts';
import { FIESTA_TENANT_ID, num as fnum, str as fstr, ymd, type Row } from '../services/fiestaApi';
import {
  GradientHeader, KpiStrip, Pill, StatusChip, MetricPill, FilterBar, TH_STYLE, TableShell,
  DELIVERY_STATUS, statusColor, BRAND, BRAND_LIGHT, TEXT, TEXT_2, TEXT_3, BORDER, DIVIDER, SURFACE_ALT, tint, soft, edge, ring,
  Skeleton, Tooltip
} from './consoleUi';

import SalesRevenueReport from './SalesRevenueReport';

type ReportTab = 'orders-summary' | 'riders-summary';
const TABS: Array<{ key: ReportTab; label: string; icon: typeof TrendingUp }> = [
  { key: 'orders-summary', label: 'Orders Summary', icon: Store },
  { key: 'riders-summary', label: 'Riders Summary', icon: Bike },
];

interface DeliveryReportsViewProps { searchQuery?: string; tenantId?: number; locationid?: number; }

export default function DeliveryReportsView({ searchQuery = '', tenantId = FIESTA_TENANT_ID, locationid }: DeliveryReportsViewProps) {
  const [activeTab, setActiveTab] = useState<'overview' | 'sales_revenue'>('overview');
  
  const today = new Date();
  const monthStart = new Date(today.getFullYear(), today.getMonth(), 1);
  const [fromdate, setFromdate] = useState<string>(ymd(monthStart));
  const [todate, setTodate] = useState<string>(ymd(today));
  const [tab, setTab] = useState<ReportTab>('orders-summary');

  const dayOffset = (n: number) => { const d = new Date(); d.setDate(d.getDate() - n); return ymd(d); };
  const presets = [
    { key: 'today', label: 'Today', from: ymd(today), to: ymd(today) },
    { key: '7d', label: 'Last 7 Days', from: dayOffset(6), to: ymd(today) },
    { key: '30d', label: 'Last 30 Days', from: dayOffset(29), to: ymd(today) },
    { key: 'month', label: 'This Month', from: ymd(monthStart), to: ymd(today) },
  ];
  const activePreset = presets.find((p) => p.from === fromdate && p.to === todate)?.key ?? 'custom';


  return (
    <div className="animate-in fade-in duration-300">
      <div className="flex items-center gap-4 border-b border-slate-200/70 pb-2 mb-4">
        <button 
          onClick={() => setActiveTab('overview')} 
          className={`pb-2 text-sm font-bold border-b-2 transition-colors ${activeTab === 'overview' ? 'border-[#662582] text-[#662582]' : 'border-transparent text-slate-500 hover:text-slate-700'}`}
        >
          Overview
        </button>
        <button 
          onClick={() => setActiveTab('sales_revenue')} 
          className={`pb-2 text-sm font-bold border-b-2 transition-colors ${activeTab === 'sales_revenue' ? 'border-[#662582] text-[#662582]' : 'border-transparent text-slate-500 hover:text-slate-700'}`}
        >
          Sales & Revenue
        </button>
      </div>

      {activeTab === 'overview' ? (
        <>
      {/* Tab nav & Date range combined */}
      <FilterBar className="mb-4">
        <div className="flex flex-col lg:flex-row lg:items-center justify-between gap-4">
          <div className="flex items-center gap-2 overflow-x-auto shrink-0">
            {TABS.map((t) => {
              const Icon = t.icon;
              return (
                <React.Fragment key={t.key}>
                  <Pill active={tab === t.key} color={BRAND} onClick={() => setTab(t.key)}><Icon size={14} /> {t.label}</Pill>
                </React.Fragment>
              );
            })}
          </div>

          <div className="flex items-center gap-4 flex-wrap lg:justify-end min-w-0">
            <div className="flex items-center gap-2 flex-wrap">
              <span className="hidden sm:inline-flex items-center gap-1.5 text-[10px] font-extrabold uppercase tracking-widest pr-1" style={{ color: TEXT_2 }}><Calendar size={13} style={{ color: BRAND }} /> Period</span>
              {presets.map((p) => (
                <React.Fragment key={p.key}><Pill active={activePreset === p.key} color={BRAND} onClick={() => { setFromdate(p.from); setTodate(p.to); }}>{p.label}</Pill></React.Fragment>
              ))}
            </div>
            <div className="flex items-center gap-2 text-xs">
              <input type="date" value={fromdate} max={todate} onChange={(e) => setFromdate(e.target.value)} className="rounded-full outline-none font-semibold w-28 sm:w-auto" style={{ padding: '6px 12px', border: `1.5px solid ${edge('#f59e0b')}`, background: tint('#f59e0b'), color: '#b45309' }} />
              <span style={{ color: TEXT_3 }}>→</span>
              <input type="date" value={todate} min={fromdate} max={ymd(today)} onChange={(e) => setTodate(e.target.value)} className="rounded-full outline-none font-semibold w-28 sm:w-auto" style={{ padding: '6px 12px', border: `1.5px solid ${edge('#f59e0b')}`, background: tint('#f59e0b'), color: '#b45309' }} />
            </div>
          </div>
        </div>
      </FilterBar>


      {tab === 'orders-summary' && <OrdersSummaryReport tenantId={tenantId} locationid={locationid} fromdate={fromdate} todate={todate} />}
      {tab === 'riders-summary' && <RidersSummaryReport fromdate={fromdate} todate={todate} tenantId={tenantId} locationid={locationid} />}
        </>
      ) : (
        <SalesRevenueReport tenantId={tenantId} locationid={locationid} />
      )}
    </div>
  );
}

const Cnt = ({ n, color }: { n: number; color: string }) => (
  n > 0 ? <span className="inline-flex items-center justify-center px-2 py-0.5 rounded-md font-bold text-xs" style={{ backgroundColor: `${color}15`, color }}>{n.toLocaleString('en-IN')}</span> : <span className="font-bold text-slate-300 text-xs">0</span>
);

// ── Orders Summary (per outlet) ──────────────────────────────────────────────────
function OrdersSummaryReport({ tenantId, locationid, fromdate, todate }: { tenantId: number; locationid?: number; fromdate: string; todate: string; }) {
  const [metric, setMetric] = useState<'revenue' | 'orders'>('revenue');

  const q = useFiestaLocationSummary(tenantId, fromdate, todate);
  const ordersQ = useFiestaAllOrders({ tenantid: tenantId, fromdate, todate, locationid });
  const revenueQ = useFiestaRevenueSummary({ tenantid: tenantId, locationid, fromdate, todate });

  const rows = (q.data ?? []).filter(r => locationid ? r.locationid === locationid : true);
  const totals = rows.reduce((a, r) => ({ total: a.total + r.total, pending: a.pending + r.pending, delivered: a.delivered + r.delivered, cancelled: a.cancelled + r.cancelled }), { total: 0, pending: 0, delivered: 0, cancelled: 0 });

  // Compute trend data
  const chartData = useMemo(() => {
    const map = new Map<string, { date: string; orders: number; revenue: number }>();
    for (const r of (ordersQ.data ?? [])) {
      const dateVal = fstr(r.orderdate) || fstr(r.deliverydate);
      if (!dateVal) continue;
      const key = dateVal.split('T')[0];

      const ex = map.get(key) || { date: key, orders: 0, revenue: 0 };
      ex.orders += 1;
      const amt = fnum(r.ordervalue) || fnum(r.orderamount) || fnum(r.deliveryamt);
      ex.revenue += amt;
      map.set(key, ex);
    }
    return Array.from(map.values()).sort((a, b) => a.date.localeCompare(b.date));
  }, [ordersQ.data]);

  const formatLabel = (key: string) => {
    const d = new Date(key);
    const months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
    return `${d.getDate()} ${months[d.getMonth()]}`;
  };

  const totalRevenue = revenueQ.data?.overallrevenue ?? 0;
  const locationRevenueMap = useMemo(() => {
    const map = new Map<number, number>();
    for (const r of (ordersQ.data ?? [])) {
      const loc = fnum(r.locationid) || fnum(r.applocationid);
      const amt = fnum(r.ordervalue) || fnum(r.orderamount) || fnum(r.deliveryamt) || fnum(r.collectionamt);
      if (loc && amt) {
        map.set(loc, (map.get(loc) || 0) + amt);
      }
    }
    return map;
  }, [ordersQ.data]);

  const metricColor = metric === 'revenue' ? '#4f46e5' : '#0ea5e9';

  // Computed Advanced Metrics
  const aov = totals.total > 0 ? totalRevenue / totals.total : 0;
  const cancelRate = totals.total > 0 ? (totals.cancelled / totals.total) * 100 : 0;
  
  const hourlyData = useMemo(() => {
    const hours = new Array(24).fill(0);
    for (const r of (ordersQ.data ?? [])) {
      const dateVal = fstr(r.orderdate) || fstr(r.deliverydate) || fstr(r.createdat);
      if (!dateVal) continue;
      const timePart = dateVal.split('T')[1];
      if (timePart) {
        // Adjust based on the actual timezone if needed, assuming UTC -> local roughly or just raw hour
        const hour = parseInt(timePart.split(':')[0], 10);
        if (!isNaN(hour) && hour >= 0 && hour <= 23) {
          hours[hour] += 1;
        }
      }
    }
    // Combine hours into something more readable or just raw 24h
    return hours.map((count, hour) => {
      const ampm = hour >= 12 ? 'PM' : 'AM';
      const h12 = hour % 12 || 12;
      return { hourLabel: `${h12}${ampm}`, count };
    });
  }, [ordersQ.data]);

  const statusData = [
    { name: 'Delivered', value: totals.delivered, color: '#10b981' },
    { name: 'Processing', value: totals.total - totals.delivered - totals.pending - totals.cancelled, color: '#6366f1' },
    { name: 'Pending', value: totals.pending, color: '#f59e0b' },
    { name: 'Cancelled', value: totals.cancelled, color: '#ef4444' },
  ].filter(d => d.value > 0);

  return (
    <div className="space-y-6">
      <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-4">
        {/* Revenue */}
        <button onClick={() => setMetric('revenue')} className={`rounded-xl p-3 flex flex-col justify-between transition-all duration-300 text-left cursor-pointer outline-none relative group border ${metric === 'revenue' ? 'border-indigo-200 bg-white shadow-[0_8px_24px_rgba(99,102,241,0.12)] ring-1 ring-indigo-500/20 z-10' : 'border-slate-200/70 bg-white hover:border-indigo-200 hover:shadow-[0_8px_24px_rgba(99,102,241,0.06)] opacity-70 hover:opacity-100'}`}>
          <div className="flex justify-between items-start w-full">
            <Tooltip content="Total revenue collected across all orders (excluding cancelled) in this period." position="bottom">
              <span className="text-[10px] text-slate-500 uppercase tracking-widest font-bold">Revenue</span>
            </Tooltip>
            <div className={`p-1.5 rounded-lg transition-transform group-hover:scale-110 flex items-center justify-center shrink-0 ${metric === 'revenue' ? 'bg-indigo-100 text-indigo-700' : 'bg-indigo-50 text-indigo-600'}`}>
              <IndianRupee className="w-3.5 h-3.5" />
            </div>
          </div>
          <div className="mt-2 w-full">
            <h3 className="text-lg font-extrabold tracking-tight font-mono text-slate-900 truncate">
              ₹{totalRevenue.toLocaleString('en-IN')}
            </h3>
            <p className="text-[10px] text-slate-400 font-semibold mt-0.5">Total collected</p>
          </div>
        </button>

        {/* Orders */}
        <button onClick={() => setMetric('orders')} className={`rounded-xl p-3 flex flex-col justify-between transition-all duration-300 text-left cursor-pointer outline-none relative group border ${metric === 'orders' ? 'border-sky-200 bg-white shadow-[0_8px_24px_rgba(14,165,233,0.12)] ring-1 ring-sky-500/20 z-10' : 'border-slate-200/70 bg-white hover:border-sky-200 hover:shadow-[0_8px_24px_rgba(14,165,233,0.06)] opacity-70 hover:opacity-100'}`}>
          <div className="flex justify-between items-start w-full">
            <Tooltip content="Total number of orders placed in this period, regardless of current status." position="bottom">
              <span className="text-[10px] text-slate-500 uppercase tracking-widest font-bold">Total Orders</span>
            </Tooltip>
            <div className={`p-1.5 rounded-lg transition-transform group-hover:scale-110 flex items-center justify-center shrink-0 ${metric === 'orders' ? 'bg-sky-100 text-sky-700' : 'bg-sky-50 text-sky-600'}`}>
              <TrendingUp className="w-3.5 h-3.5" />
            </div>
          </div>
          <div className="mt-2 w-full">
            <h3 className="text-lg font-extrabold tracking-tight font-mono text-slate-900 truncate">
              {totals.total.toLocaleString('en-IN')}
            </h3>
            <p className="text-[10px] text-slate-400 font-semibold mt-0.5">All statuses</p>
          </div>
        </button>

        {/* AOV */}
        <div className="rounded-xl p-3 flex flex-col justify-between transition-all duration-300 text-left relative group border border-slate-200/70 bg-white hover:border-violet-200 hover:shadow-[0_8px_24px_rgba(139,92,246,0.06)] opacity-70 hover:opacity-100">
          <div className="flex justify-between items-start w-full">
            <Tooltip content="Average revenue generated per order (Total Revenue ÷ Total Orders)." position="bottom">
              <span className="text-[10px] text-slate-500 uppercase tracking-widest font-bold">Avg Order Value</span>
            </Tooltip>
            <div className="p-1.5 rounded-lg transition-transform group-hover:scale-110 flex items-center justify-center shrink-0 bg-violet-50 text-violet-600">
              <TrendingUp className="w-3.5 h-3.5" />
            </div>
          </div>
          <div className="mt-2 w-full">
            <h3 className="text-lg font-extrabold tracking-tight font-mono text-slate-900 truncate">
              ₹{Math.round(aov).toLocaleString('en-IN')}
            </h3>
            <p className="text-[10px] text-slate-400 font-semibold mt-0.5">Per order</p>
          </div>
        </div>

        {/* Delivered */}
        <div className="rounded-xl p-3 flex flex-col justify-between transition-all duration-300 text-left relative group border border-slate-200/70 bg-white hover:border-emerald-200 hover:shadow-[0_8px_24px_rgba(16,185,129,0.06)] opacity-70 hover:opacity-100">
          <div className="flex justify-between items-start w-full">
            <Tooltip content="Total number of orders successfully delivered to the customer." position="bottom">
              <span className="text-[10px] text-slate-500 uppercase tracking-widest font-bold">Delivered</span>
            </Tooltip>
            <div className="p-1.5 rounded-lg transition-transform group-hover:scale-110 flex items-center justify-center shrink-0 bg-emerald-50 text-emerald-600">
              <CheckCircle2 className="w-3.5 h-3.5" />
            </div>
          </div>
          <div className="mt-2 w-full">
            <h3 className="text-lg font-extrabold tracking-tight font-mono text-slate-900 truncate">
              {totals.delivered.toLocaleString('en-IN')}
            </h3>
            <p className="text-[10px] text-slate-400 font-semibold mt-0.5">Successfully fulfilled</p>
          </div>
        </div>

        {/* Pending */}
        <div className="rounded-xl p-3 flex flex-col justify-between transition-all duration-300 text-left relative group border border-slate-200/70 bg-white hover:border-amber-200 hover:shadow-[0_8px_24px_rgba(245,158,11,0.06)] opacity-70 hover:opacity-100">
          <div className="flex justify-between items-start w-full">
            <Tooltip content="Total number of orders currently being prepared, picked up, or in transit." position="bottom">
              <span className="text-[10px] text-slate-500 uppercase tracking-widest font-bold">Pending</span>
            </Tooltip>
            <div className="p-1.5 rounded-lg transition-transform group-hover:scale-110 flex items-center justify-center shrink-0 bg-amber-50 text-amber-600">
              <Clock className="w-3.5 h-3.5" />
            </div>
          </div>
          <div className="mt-2 w-full">
            <h3 className="text-lg font-extrabold tracking-tight font-mono text-slate-900 truncate">
              {totals.pending.toLocaleString('en-IN')}
            </h3>
            <p className="text-[10px] text-slate-400 font-semibold mt-0.5">In progress</p>
          </div>
        </div>

        {/* Cancel Rate */}
        <div className="rounded-xl p-3 flex flex-col justify-between transition-all duration-300 text-left relative group border border-slate-200/70 bg-white hover:border-rose-200 hover:shadow-[0_8px_24px_rgba(244,63,94,0.06)] opacity-70 hover:opacity-100">
          <div className="flex justify-between items-start w-full">
            <Tooltip content="Percentage of total orders that were cancelled (Cancelled ÷ Total Orders × 100)." position="bottom">
              <span className="text-[10px] text-slate-500 uppercase tracking-widest font-bold">Cancel Rate</span>
            </Tooltip>
            <div className={`p-1.5 rounded-lg transition-transform group-hover:scale-110 flex items-center justify-center shrink-0 ${cancelRate > 10 ? 'bg-rose-100 text-rose-700' : 'bg-slate-50 text-slate-500'}`}>
              <svg className="w-3.5 h-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3Z"/><path d="M12 9v4"/><path d="M12 17h.01"/></svg>
            </div>
          </div>
          <div className="mt-2 w-full">
            <h3 className={`text-lg font-extrabold tracking-tight font-mono truncate ${cancelRate > 10 ? 'text-rose-600' : 'text-slate-900'}`}>
              {cancelRate.toFixed(1)}%
            </h3>
            <p className="text-[10px] text-slate-400 font-semibold mt-0.5">Cancelled orders</p>
          </div>
        </div>
      </div>

      <div className="bg-white rounded-2xl border border-slate-200 shadow-sm overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full text-sm text-left">
            <thead className="bg-slate-50 border-b border-slate-200 text-xs font-semibold text-slate-500 uppercase tracking-wider">
              <tr>
                <th className="px-5 py-4 w-12">#</th>
                <th className="px-5 py-4">Outlet</th>
                <th className="px-5 py-4 text-right">Revenue</th>
                <th className="px-5 py-4 text-right">AOV</th>
                <th className="px-5 py-4 text-right">Orders</th>
                <th className="px-5 py-4 text-right">Fulfillment</th>
                <th className="px-5 py-4 text-right">Cancel Rate</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-100">
              {q.isLoading || revenueQ.isLoading ? <tr><td colSpan={7} className="px-5 py-6"><div className="space-y-3"><Skeleton className="h-5 w-full" /><Skeleton className="h-5 w-full opacity-70" /><Skeleton className="h-5 w-full opacity-40" /></div></td></tr>
                : rows.length === 0 ? <tr><td colSpan={7} className="px-5 py-12 text-center text-slate-500 font-medium">No outlet data available.</td></tr>
                : rows.map((r, i) => {
                    const rowRev = locationRevenueMap.get(fnum(r.locationid)) ?? 0;
                    const rowAov = r.total > 0 ? rowRev / r.total : 0;
                    const rowFulfill = r.total > 0 ? (r.delivered / r.total) * 100 : 0;
                    const rowCancel = r.total > 0 ? (r.cancelled / r.total) * 100 : 0;
                    return (
                      <tr key={r.locationid || i} className="hover:bg-slate-50 transition-colors">
                        <td className="px-5 py-3 text-slate-400 font-medium">{i + 1}</td>
                        <td className="px-5 py-3 font-semibold text-slate-900">{r.locationname || `Location ${r.locationid}`}</td>
                        <td className="px-5 py-3 text-right font-bold text-indigo-600">₹{rowRev.toLocaleString('en-IN')}</td>
                        <td className="px-5 py-3 text-right text-slate-600 font-medium">₹{Math.round(rowAov).toLocaleString('en-IN')}</td>
                        <td className="px-5 py-3 text-right font-bold text-slate-900">{r.total.toLocaleString('en-IN')}</td>
                        <td className="px-5 py-3 text-right">
                          <div className="flex items-center justify-end gap-2">
                            <span className="text-xs font-bold text-emerald-600">{rowFulfill.toFixed(0)}%</span>
                            <div className="w-16 h-1.5 bg-slate-100 rounded-full overflow-hidden">
                              <div className="h-full bg-emerald-500 rounded-full" style={{ width: `${rowFulfill}%` }} />
                            </div>
                          </div>
                        </td>
                        <td className="px-5 py-3 text-right">
                          <span className={`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-bold ${rowCancel > 10 ? 'bg-rose-100 text-rose-700' : 'bg-slate-100 text-slate-600'}`}>
                            {rowCancel.toFixed(1)}%
                          </span>
                        </td>
                      </tr>
                    );
                })}
            </tbody>
          </table>
        </div>
        {rows.length > 0 && (
          <div className="bg-slate-50 border-t border-slate-200 px-5 py-3 flex items-center gap-4 text-sm font-medium">
            <span className="text-slate-500">Totals:</span>
            <span className="text-indigo-600 font-bold">₹{totalRevenue.toLocaleString('en-IN')}</span>
            <span className="text-slate-900 font-bold">{totals.total} orders</span>
            <span className="text-emerald-600 font-bold">{totals.delivered} delivered</span>
            <span className="text-amber-600 font-bold">{totals.pending} pending</span>
          </div>
        )}
      </div>

      {/* Insights Bento */}
      <div className="grid grid-cols-1 xl:grid-cols-3 gap-6">
        
        {/* Trend Chart */}
        <div className="xl:col-span-2 bg-white rounded-2xl border border-slate-200 shadow-sm p-6 flex flex-col">
          <div className="flex items-center gap-2 mb-6">
            <TrendingUp size={18} className="text-indigo-500" />
            <h3 className="text-sm font-bold text-slate-900 tracking-tight uppercase">Performance Trend</h3>
          </div>
          <div className="w-full h-72">
            {ordersQ.isLoading ? (
               <Skeleton className="w-full h-[240px] rounded-xl" />
            ) : chartData.length === 0 ? (
               <div className="w-full h-full flex items-center justify-center text-sm font-medium text-slate-500">No trend data for this period.</div>
            ) : (
              <ResponsiveContainer width="100%" height="100%">
                <AreaChart data={chartData} margin={{ top: 10, right: 10, left: 0, bottom: 0 }}>
                  <defs>
                    <linearGradient id="colorGradient" x1="0" y1="0" x2="0" y2="1">
                      <stop offset="5%" stopColor={metricColor} stopOpacity={0.2} />
                      <stop offset="95%" stopColor={metricColor} stopOpacity={0} />
                    </linearGradient>
                  </defs>
                  <CartesianGrid strokeDasharray="4 4" vertical={false} stroke="#e2e8f0" />
                  <XAxis dataKey="date" axisLine={false} tickLine={false} tick={{ fontSize: 11, fill: '#64748b', fontWeight: 500 }} dy={10} 
                    tickFormatter={formatLabel} />
                  <YAxis axisLine={false} tickLine={false} tick={{ fontSize: 11, fill: '#64748b', fontWeight: 500 }} dx={-10} tickFormatter={(v) => metric === 'revenue' ? `₹${v.toLocaleString('en-IN')}` : v.toLocaleString('en-IN')} />
                  <RechartsTooltip 
                    cursor={{ stroke: metricColor, strokeWidth: 1, strokeDasharray: '4 4' }}
                    content={({ active, payload, label }: any) => {
                      if (active && payload && payload.length) {
                        return (
                          <div className="bg-white p-3 rounded-xl border border-slate-200 shadow-lg">
                            <p className="text-[10px] font-bold text-slate-400 uppercase tracking-wider mb-2">{formatLabel(label)}</p>
                            <div className="flex flex-col gap-1">
                              <span className="flex items-center gap-1.5 text-xs font-bold text-slate-600 capitalize">
                                <span className="w-2 h-2 rounded-full" style={{ backgroundColor: metricColor }}></span>
                                {metric}
                              </span>
                              <span className="text-base font-black text-slate-900">
                                {metric === 'revenue' ? `₹${payload[0].value.toLocaleString('en-IN')}` : payload[0].value.toLocaleString('en-IN')}
                              </span>
                            </div>
                          </div>
                        );
                      }
                      return null;
                    }}
                  />
                  <Area type="monotone" dataKey={metric} stroke={metricColor} strokeWidth={2.5} fillOpacity={1} fill="url(#colorGradient)" activeDot={{ r: 5, strokeWidth: 2, stroke: '#fff', fill: metricColor }} />
                </AreaChart>
              </ResponsiveContainer>
            )}
          </div>
        </div>

        {/* Breakdown Stack */}
        <div className="flex flex-col gap-6">
          {/* Status Breakdown */}
          <div className="bg-white rounded-2xl border border-slate-200 shadow-sm p-5 flex flex-col flex-1">
            <div className="flex items-center gap-2 mb-4">
              <CheckCircle2 size={16} className="text-emerald-500" />
              <h3 className="text-xs font-bold text-slate-900 tracking-tight uppercase">Order Status</h3>
            </div>
            {statusData.length > 0 ? (
              <div className="w-full h-40">
                <ResponsiveContainer width="100%" height="100%">
                  <PieChart>
                    <Pie data={statusData} cx="50%" cy="50%" innerRadius={35} outerRadius={60} dataKey="value" paddingAngle={3} stroke="none">
                      {statusData.map((entry, index) => (
                        <Cell key={`cell-${index}`} fill={entry.color} />
                      ))}
                    </Pie>
                    <RechartsTooltip formatter={(value: number) => value.toLocaleString('en-IN')} contentStyle={{ borderRadius: '12px', border: '1px solid #e2e8f0', boxShadow: '0 4px 6px -1px rgba(0, 0, 0, 0.1)' }} itemStyle={{ fontWeight: 'bold' }} />
                  </PieChart>
                </ResponsiveContainer>
              </div>
            ) : (
              <div className="flex-1 flex items-center justify-center text-xs text-slate-400">No data</div>
            )}
            <div className="flex flex-wrap justify-center gap-x-4 gap-y-2 mt-auto">
              {statusData.map(s => (
                <div key={s.name} className="flex items-center gap-1.5 text-[10px] font-bold text-slate-600">
                  <span className="w-2 h-2 rounded-full" style={{ backgroundColor: s.color }} /> {s.name} ({s.value})
                </div>
              ))}
            </div>
          </div>

          {/* Hourly Heatmap (Bar) */}
          <div className="bg-white rounded-2xl border border-slate-200 shadow-sm p-5 flex flex-col flex-1">
            <div className="flex items-center gap-2 mb-2">
              <Clock size={16} className="text-amber-500" />
              <h3 className="text-xs font-bold text-slate-900 tracking-tight uppercase">Peak Hours</h3>
            </div>
            <div className="w-full h-40 mt-auto">
              {ordersQ.isLoading ? (
                 <Skeleton className="w-full h-[240px] rounded-xl" />
              ) : (
                <ResponsiveContainer width="100%" height="100%">
                  <BarChart data={hourlyData} margin={{ top: 10, right: 0, left: -25, bottom: 0 }}>
                    <CartesianGrid strokeDasharray="3 3" vertical={false} stroke="#f1f5f9" />
                    <XAxis dataKey="hourLabel" axisLine={false} tickLine={false} tick={{ fontSize: 9, fill: '#94a3b8', fontWeight: 600 }} interval="preserveStartEnd" minTickGap={10} />
                    <YAxis axisLine={false} tickLine={false} tick={{ fontSize: 9, fill: '#94a3b8' }} />
                    <RechartsTooltip cursor={{ fill: '#f8fafc' }} contentStyle={{ borderRadius: '8px', border: 'none', boxShadow: '0 4px 6px -1px rgba(0,0,0,0.1)' }} />
                    <Bar dataKey="count" fill="#6366f1" radius={[3, 3, 0, 0]} />
                  </BarChart>
                </ResponsiveContainer>
              )}
            </div>
          </div>
        </div>

      </div>
    </div>
  );
}

// ── Riders Summary (per rider) ───────────────────────────────────────────────────
function RidersSummaryReport({ fromdate, todate, tenantId, locationid }: { fromdate: string; todate: string; tenantId: number; locationid?: number }) {
  const q = useFiestaFleetSummary({ tenantid: tenantId, fromdate, todate });
  const rows = q.data ?? [];
  const mapped = rows.map((r) => ({
    name: fstr(r.fullname) || `${fstr(r.firstname)} ${fstr(r.lastname)}`.trim() || fstr(r.username) || `Rider ${fstr(r.userid)}`,
    orders: fnum(r.totalorders) || fnum(r.orders), delivered: fnum(r.delivered) || fnum(r.deliveriescompleted) || fnum(r.completed),
    pending: fnum(r.pending) || fnum(r.deliveriespending), cancelled: fnum(r.cancelled) || fnum(r.deliveriescancelled),
    kms: fnum(r.kms), actualKms: fnum(r.cumulativekms), amount: fnum(r.deliveryamt) || fnum(r.charges) || fnum(r.deliverycharges),
  }));
  const totals = mapped.reduce((a, r) => ({ orders: a.orders + r.orders, delivered: a.delivered + r.delivered, amount: a.amount + r.amount }), { orders: 0, delivered: 0, amount: 0 });
  const kpis = [
    { label: 'Active Riders', value: mapped.length.toLocaleString('en-IN'), color: BRAND, icon: <Bike size={20} /> },
    { label: 'Total Orders', value: totals.orders.toLocaleString('en-IN'), color: '#0ea5e9', icon: <Truck size={20} /> },
    { label: 'Delivered', value: totals.delivered.toLocaleString('en-IN'), color: '#10b981', icon: <CheckCircle2 size={20} /> },
    { label: 'Total Amount', value: `₹${totals.amount.toLocaleString('en-IN')}`, color: '#f59e0b', icon: <IndianRupee size={20} /> },
  ];
  return (
    <div className="space-y-4">
      <KpiStrip items={kpis} loading={q.isLoading} />
      <TableShell minWidth={820} head={['#', 'Rider', 'Orders', 'Pending', 'Cancelled', 'Delivered', 'KMs', 'Amount']}
        footer={mapped.length > 0 ? <TotalBar chips={[{ label: `${totals.orders} orders`, color: BRAND }, { label: `${totals.delivered} delivered`, color: '#10b981' }]} grand={`₹${totals.amount.toLocaleString('en-IN')}`} /> : undefined}>
        {q.isLoading ? <tr><td colSpan={8} className="px-5 py-6"><div className="space-y-3"><Skeleton className="h-5 w-full" /><Skeleton className="h-5 w-full opacity-70" /><Skeleton className="h-5 w-full opacity-40" /></div></td></tr>
          : q.isError ? <tr><td colSpan={8} className="px-3 py-12 text-center text-xs" style={{ color: '#ef4444' }}>Rider summary unavailable for this period.</td></tr>
          : mapped.length === 0 ? <tr><td colSpan={8} className="px-3 py-12 text-center text-xs" style={{ color: TEXT_3 }}>No rider activity in this period.</td></tr>
          : mapped.map((r, i) => (
            <tr key={i} className="transition-colors" style={{ borderBottom: `1px solid ${DIVIDER}` }} onMouseEnter={(e) => (e.currentTarget.style.background = SURFACE_ALT)} onMouseLeave={(e) => (e.currentTarget.style.background = 'transparent')}>
              <td className="px-3 py-2.5 font-mono" style={{ color: TEXT_3 }}>{i + 1}</td>
              <td className="px-3 py-2.5">
                <span className="inline-flex items-center gap-2">
                  <span className="rounded-full flex items-center justify-center shrink-0" style={{ width: 26, height: 26, background: soft('#8b5cf6'), color: '#8b5cf6' }}><Bike size={13} /></span>
                  <span className="font-extrabold text-[13px]" style={{ color: TEXT }}>{r.name}</span>
                </span>
              </td>
              <td className="px-3 py-2.5 text-right font-extrabold font-mono" style={{ color: TEXT }}>{r.orders.toLocaleString('en-IN')}</td>
              <td className="px-3 py-2.5 text-right"><Cnt n={r.pending} color="#f59e0b" /></td>
              <td className="px-3 py-2.5 text-right"><Cnt n={r.cancelled} color="#ef4444" /></td>
              <td className="px-3 py-2.5 text-right"><Cnt n={r.delivered} color="#10b981" /></td>
              <td className="px-3 py-2.5 text-right font-mono text-xs" style={{ color: TEXT_2 }}>{r.kms ? r.kms.toFixed(1) : '—'}{r.actualKms > 0 ? ` / ${r.actualKms.toFixed(1)}` : ''}</td>
              <td className="px-3 py-2.5 text-right">{r.amount > 0 ? <MetricPill color="#10b981" minWidth={72}>₹{r.amount.toLocaleString('en-IN')}</MetricPill> : <span style={{ color: TEXT_3 }}>—</span>}</td>
            </tr>
          ))}
      </TableShell>
    </div>
  );
}



// ── Total bar (gradient) ─────────────────────────────────────────────────────────
function TotalBar({ chips, grand }: { chips: Array<{ label: string; color: string }>; grand?: string }) {
  return (
    <div className="flex items-center justify-between flex-wrap gap-2 px-4 py-3 border-t" style={{ borderColor: BORDER, background: `linear-gradient(135deg, ${tint(BRAND)} 0%, ${tint(BRAND_LIGHT)} 100%)` }}>
      <div className="flex items-center gap-2 flex-wrap">
        {chips.map((c, i) => (
          <span key={i} className="inline-flex items-center rounded-full font-bold" style={{ padding: '3px 10px', fontSize: 11.5, background: soft(c.color), color: c.color, border: `1px solid ${edge(c.color)}` }}>{c.label}</span>
        ))}
      </div>
      {grand && (
        <span className="inline-flex items-center rounded-full font-extrabold text-white" style={{ padding: '4px 12px', fontSize: 13, background: `linear-gradient(135deg, ${BRAND}, ${BRAND_LIGHT})`, boxShadow: `0 6px 16px ${ring(BRAND)}` }}>{grand}</span>
      )}
    </div>
  );
}
