/**
 * @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, XAxis, YAxis, Tooltip as RechartsTooltip, CartesianGrid } 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,
} from './consoleUi';

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 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">
      <GradientHeader title="Reports" subtitle="Operational analytics across outlets, riders, and the full order lifecycle." />

      {/* Tab nav */}
      <FilterBar className="mb-4">
        <div className="flex items-center gap-2 overflow-x-auto">
          {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>
      </FilterBar>

      {/* Shared date range */}
      <FilterBar className="mb-4">
        <div className="flex flex-col lg:flex-row lg:items-center justify-between gap-3">
          <div className="flex items-center gap-2 flex-wrap">
            <span className="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" 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" style={{ padding: '6px 12px', border: `1.5px solid ${edge('#f59e0b')}`, background: tint('#f59e0b'), color: '#b45309' }} />
          </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} />}
    </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);
  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?.grossrevenue ?? 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';

  return (
    <div className="space-y-6">
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        <button onClick={() => setMetric('revenue')} className={`text-left p-5 bg-white rounded-2xl border transition-all duration-200 cursor-pointer flex items-center gap-4 ${metric === 'revenue' ? 'border-indigo-500 shadow-md ring-1 ring-indigo-500' : 'border-slate-200 shadow-sm hover:shadow-md'}`}>
          <div className={`p-3 rounded-xl ${metric === 'revenue' ? 'bg-indigo-100 text-indigo-600' : 'bg-slate-50 text-slate-400'}`}><IndianRupee size={20} /></div>
          <div>
            <p className="text-sm font-medium text-slate-500">Revenue</p>
            <p className="text-2xl font-bold tracking-tight text-slate-900 mt-0.5">₹{totalRevenue.toLocaleString('en-IN')}</p>
          </div>
        </button>
        <button onClick={() => setMetric('orders')} className={`text-left p-5 bg-white rounded-2xl border transition-all duration-200 cursor-pointer flex items-center gap-4 ${metric === 'orders' ? 'border-sky-500 shadow-md ring-1 ring-sky-500' : 'border-slate-200 shadow-sm hover:shadow-md'}`}>
          <div className={`p-3 rounded-xl ${metric === 'orders' ? 'bg-sky-100 text-sky-600' : 'bg-slate-50 text-slate-400'}`}><TrendingUp size={20} /></div>
          <div>
            <p className="text-sm font-medium text-slate-500">Total Orders</p>
            <p className="text-2xl font-bold tracking-tight text-slate-900 mt-0.5">{totals.total.toLocaleString('en-IN')}</p>
          </div>
        </button>
        <div className="p-5 bg-white rounded-2xl border border-slate-200 shadow-sm flex items-center gap-4">
          <div className="p-3 rounded-xl bg-amber-50 text-amber-600"><Clock size={20} /></div>
          <div>
            <p className="text-sm font-medium text-slate-500">Pending</p>
            <p className="text-2xl font-bold tracking-tight text-slate-900 mt-0.5">{totals.pending.toLocaleString('en-IN')}</p>
          </div>
        </div>
        <div className="p-5 bg-white rounded-2xl border border-slate-200 shadow-sm flex items-center gap-4">
          <div className="p-3 rounded-xl bg-emerald-50 text-emerald-600"><CheckCircle2 size={20} /></div>
          <div>
            <p className="text-sm font-medium text-slate-500">Delivered</p>
            <p className="text-2xl font-bold tracking-tight text-slate-900 mt-0.5">{totals.delivered.toLocaleString('en-IN')}</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">All</th>
                <th className="px-5 py-4 text-right">Created</th>
                <th className="px-5 py-4 text-right">Pending</th>
                <th className="px-5 py-4 text-right">Processing</th>
                <th className="px-5 py-4 text-right">Delivered</th>
                <th className="px-5 py-4 text-right">Cancelled</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-100">
              {q.isLoading || revenueQ.isLoading ? <tr><td colSpan={9} className="px-5 py-12 text-center text-slate-500 font-medium">Loading outlet summary…</td></tr>
                : rows.length === 0 ? <tr><td colSpan={9} className="px-5 py-12 text-center text-slate-500 font-medium">No outlet data available.</td></tr>
                : rows.map((r, i) => (
                  <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">₹{(locationRevenueMap.get(fnum(r.locationid)) ?? 0).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"><Cnt n={r.created} color="#0ea5e9" /></td>
                    <td className="px-5 py-3 text-right"><Cnt n={r.pending} color="#f59e0b" /></td>
                    <td className="px-5 py-3 text-right"><Cnt n={r.processing} color="#6366f1" /></td>
                    <td className="px-5 py-3 text-right"><Cnt n={r.delivered} color="#10b981" /></td>
                    <td className="px-5 py-3 text-right"><Cnt n={r.cancelled} color="#ef4444" /></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>

      {/* Trend Chart */}
      <div className="bg-white rounded-2xl border border-slate-200 shadow-sm p-6">
        <div className="flex items-center gap-2 mb-6">
          <TrendingUp size={20} className="text-indigo-500" />
          <h3 className="text-base font-bold text-slate-900 tracking-tight">Trend Analysis</h3>
        </div>

        <div className="w-full h-80">
          {ordersQ.isLoading ? (
             <div className="w-full h-full flex items-center justify-center text-sm font-medium text-slate-500">Loading trend data...</div>
          ) : 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: 12, fill: '#64748b', fontWeight: 500 }} dy={10} 
                  tickFormatter={formatLabel} />
                <YAxis axisLine={false} tickLine={false} tick={{ fontSize: 12, 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-4 rounded-xl border border-slate-200 shadow-lg">
                          <p className="text-xs 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-2 text-sm font-medium text-slate-600 capitalize">
                              <span className="w-2.5 h-2.5 rounded-full" style={{ backgroundColor: metricColor }}></span>
                              {metric}
                            </span>
                            <span className="text-lg font-bold 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: 6, strokeWidth: 2, stroke: '#fff', fill: metricColor }} />
              </AreaChart>
            </ResponsiveContainer>
          )}
        </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, applocationid: locationid });
  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-3 py-12 text-center text-xs" style={{ color: TEXT_3 }}>Loading rider summary…</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>
  );
}
