"use client";

import { useReducer, useCallback, useEffect } from "react";
import {
  getReportsSummary,
  getOrdersByStopReport,
  getSalesByProductReport,
  getFulfillmentReport,
  getPickupStatusByStop,
  getContactGrowthReport,
  getCampaignActivityReport,
} from "@/actions/reports";
import {
  exportOrdersByStop,
  exportSalesByProduct,
  exportPickupStatus,
  exportContactGrowth,
  exportFulfillment,
  exportCampaignActivity,
  type ReportsSummary,
  type OrderByStop,
  type SalesByProduct,
  type FulfillmentRow,
  type PickupStatusByStop,
  type ContactGrowthRow,
  type CampaignActivityRow,
} from "@/lib/reports-export";
import { formatDate, formatDateRange } from "@/lib/date-utils";
import { AdminButton, AdminFilterTabs } from "@/components/admin/design-system";

type DatePreset = "week" | "month" | "quarter" | "this_year" | "custom";

type DateRange = { start: string; end: string };

function buildRange(preset: DatePreset, customStart?: string, customEnd?: string): DateRange {
  const now = new Date();
  const toDateStr = (d: Date) => d.toISOString().slice(0, 10);
  const today = toDateStr(now);

  switch (preset) {
    case "week": {
      const s = new Date(now);
      s.setDate(s.getDate() - 6);
      return { start: toDateStr(s), end: today };
    }
    case "month": {
      const start = new Date(now.getFullYear(), now.getMonth(), 1);
      return { start: toDateStr(start), end: today };
    }
    case "quarter": {
      const q = Math.floor(now.getMonth() / 3);
      const start = new Date(now.getFullYear(), q * 3, 1);
      return { start: toDateStr(start), end: today };
    }
    case "this_year": {
      const start = new Date(now.getFullYear(), 0, 1);
      return { start: toDateStr(start), end: today };
    }
    case "custom":
      return { start: customStart ?? today, end: customEnd ?? today };
  }
}

// ── Quarter label helper ──────────────────────────────────────────────────────
function quarterLabel(startISO: string): string {
  const s = new Date(startISO + "T00:00:00");
  const q = Math.floor(s.getMonth() / 3) + 1;
  return `Q${q} ${s.getFullYear()}`;
}

function handleExportCSV(exportFn: () => string, filename: string) {
  const csv = exportFn();
  const blob = new Blob([csv], { type: "text/csv" });
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = url;
  a.download = filename;
  a.click();
  URL.revokeObjectURL(url);
}

function monthLabel(startISO: string): string {
  const s = new Date(startISO + "T00:00:00");
  return s.toLocaleDateString("en-US", { month: "long", year: "numeric" });
}

// ──────────────────────────────────────────────────────────────────────────
// State (useReducer)
// ──────────────────────────────────────────────────────────────────────────

type State = {
  preset: DatePreset;
  customStart: string;
  customEnd: string;
  selectedBrandId: string;
  activeTab: string;
  summary: ReportsSummary | null;
  ordersByStop: OrderByStop[];
  salesByProduct: SalesByProduct[];
  fulfillment: FulfillmentRow[];
  pickupStatus: PickupStatusByStop[];
  contactGrowth: ContactGrowthRow[];
  campaigns: CampaignActivityRow[];
  loading: boolean;
  error: string | null;
  explainingTab: string | null;
  explanation: { summary: string; keyInsights: string[]; suggestedActions: string[] } | null;
  explainError: string | null;
  currentYear: number;
};

type Action =
  | { type: "SET_PRESET"; value: DatePreset }
  | { type: "SET_CUSTOM_START"; value: string }
  | { type: "SET_CUSTOM_END"; value: string }
  | { type: "SET_SELECTED_BRAND_ID"; value: string }
  | { type: "SET_ACTIVE_TAB"; value: string }
  | { type: "SET_LOADING"; value: boolean }
  | { type: "SET_ERROR"; value: string | null }
  | {
      type: "SET_REPORTS";
      summary: ReportsSummary | null;
      ordersByStop: OrderByStop[];
      salesByProduct: SalesByProduct[];
      fulfillment: FulfillmentRow[];
      pickupStatus: PickupStatusByStop[];
      contactGrowth: ContactGrowthRow[];
      campaigns: CampaignActivityRow[];
    }
  | { type: "SET_EXPLAINING_TAB"; value: string | null }
  | { type: "SET_EXPLANATION"; value: { summary: string; keyInsights: string[]; suggestedActions: string[] } | null }
  | { type: "SET_EXPLAIN_ERROR"; value: string | null }
  | { type: "SET_CURRENT_YEAR"; value: number };

function makeInitialState(initialBrandId: string | null): State {
  return {
    preset: "quarter",
    customStart: "",
    customEnd: "",
    selectedBrandId: initialBrandId ?? "",
    activeTab: "overview",
    summary: null,
    ordersByStop: [],
    salesByProduct: [],
    fulfillment: [],
    pickupStatus: [],
    contactGrowth: [],
    campaigns: [],
    loading: false,
    error: null,
    explainingTab: null,
    explanation: null,
    explainError: null,
    currentYear: 0,
  };
}

function reducer(state: State, action: Action): State {
  switch (action.type) {
    case "SET_PRESET":
      return { ...state, preset: action.value };
    case "SET_CUSTOM_START":
      return { ...state, customStart: action.value };
    case "SET_CUSTOM_END":
      return { ...state, customEnd: action.value };
    case "SET_SELECTED_BRAND_ID":
      return { ...state, selectedBrandId: action.value };
    case "SET_ACTIVE_TAB":
      return { ...state, activeTab: action.value };
    case "SET_LOADING":
      return { ...state, loading: action.value };
    case "SET_ERROR":
      return { ...state, error: action.value };
    case "SET_REPORTS":
      return {
        ...state,
        summary: action.summary,
        ordersByStop: action.ordersByStop,
        salesByProduct: action.salesByProduct,
        fulfillment: action.fulfillment,
        pickupStatus: action.pickupStatus,
        contactGrowth: action.contactGrowth,
        campaigns: action.campaigns,
      };
    case "SET_EXPLAINING_TAB":
      return { ...state, explainingTab: action.value };
    case "SET_EXPLANATION":
      return { ...state, explanation: action.value };
    case "SET_EXPLAIN_ERROR":
      return { ...state, explainError: action.value };
    case "SET_CURRENT_YEAR":
      return { ...state, currentYear: action.value };
  }
}

// ── Summary card ─────────────────────────────────────────────────────────────

function SummaryCard({
  label,
  value,
  prefix,
  suffix,
}: {
  label: string;
  value: number;
  prefix?: string;
  suffix?: string;
}) {
  return (
    <div className="rounded-xl border border-zinc-800 bg-zinc-900 px-4 py-4">
      <p className="text-xs font-medium uppercase tracking-wide text-zinc-500">{label}</p>
      <p className="mt-1 text-2xl font-semibold text-zinc-100">
        {prefix ?? ""}{typeof value === "number" ? value.toLocaleString() : value}{suffix ?? ""}
      </p>
    </div>
  );
}

// ── CSV export button ───────────────────────────────────────────────────────

function ExportBtn({
  onClick,
}: {
  onClick: () => void;
}) {
  return (
    <AdminButton
      onClick={onClick}
      variant="secondary"
      size="sm"
    >
      Export CSV
    </AdminButton>
  );
}

function ExplainBtn({
  onClick,
  loading,
}: {
  onClick: () => void;
  loading: boolean;
}) {
  return (
    <AdminButton
      onClick={onClick}
      disabled={loading}
      variant="secondary"
      size="sm"
    >
      {loading ? "Analyzing..." : "🤖 Explain this Report"}
    </AdminButton>
  );
}

// ── Generic table ───────────────────────────────────────────────────────────

function ReportTable({ headers, rows, renderRow }: {
  headers: string[];
  rows: unknown[];
  renderRow: (row: unknown, i: number) => React.ReactNode;
}) {
  return (
    <div className="overflow-x-auto">
      <table className="w-full text-sm">
        <thead>
          <tr className="border-b border-zinc-800 bg-slate-50">
            {headers.map((h) => (
              <th key={h} className="px-3 py-2 text-left text-xs font-medium uppercase tracking-wide text-zinc-500">
                {h}
              </th>
            ))}
          </tr>
        </thead>
        <tbody>
          {rows.length === 0 ? (
            <tr>
              <td colSpan={headers.length} className="px-3 py-6 text-center text-slate-400">
                No data
              </td>
            </tr>
          ) : (
            rows.map((_, i) => renderRow(_, i))
          )}
        </tbody>
      </table>
    </div>
  );
}

// ── Tab definitions ─────────────────────────────────────────────────────────

const TABS = [
  { value: "overview", label: "Overview" },
  { value: "orders-by-stop", label: "Orders by Stop" },
  { value: "sales-by-product", label: "Sales by Product" },
  { value: "fulfillment", label: "Fulfillment" },
  { value: "pickup-status", label: "Pickup Status" },
  { value: "contact-growth", label: "Contact Growth" },
  { value: "campaigns", label: "Campaigns" },
];

// ──────────────────────────────────────────────────────────────────────────
// Main component
// ──────────────────────────────────────────────────────────────────────────

export default function ReportsDashboard({
  brands,
  initialBrandId,
  isPlatformAdmin,
  brandId,
}: {
  brands: { id: string; name: string }[];
  initialBrandId: string | null;
  isPlatformAdmin: boolean;
  brandId?: string | null;
}) {
  const [state, dispatch] = useReducer(reducer, initialBrandId, makeInitialState);

  const range: DateRange = buildRange(state.preset, state.customStart, state.customEnd);

  // Year is read from the clock; compute in the browser only to avoid
  // hydration mismatches with the server. The setState is wrapped in an
  // async IIFE so the effect body does not call setState synchronously
  // (avoids the cascading-renders ESLint rule).
  useEffect(() => {
    void (async () => {
      dispatch({ type: "SET_CURRENT_YEAR", value: new Date().getFullYear() });
    })();
  }, []);

  // Stable memoized fetchAll — re-fetches when range or brand changes
  const fetchAll = useCallback(async () => {
    dispatch({ type: "SET_LOADING", value: true });
    dispatch({ type: "SET_ERROR", value: null });

    const brandId = state.selectedBrandId || null;

    try {
      const [sum, obs, sbp, ful, ps, cg, cam] = await Promise.all([
        getReportsSummary(range, state.selectedBrandId || null),
        getOrdersByStopReport(range, state.selectedBrandId || null),
        getSalesByProductReport(range, state.selectedBrandId || null),
        getFulfillmentReport(range, state.selectedBrandId || null),
        getPickupStatusByStop(range, state.selectedBrandId || null),
        getContactGrowthReport(range, state.selectedBrandId || null),
        getCampaignActivityReport(range, state.selectedBrandId || null),
      ]);
      dispatch({
        type: "SET_REPORTS",
        summary: sum,
        ordersByStop: obs,
        salesByProduct: sbp,
        fulfillment: ful,
        pickupStatus: ps,
        contactGrowth: cg,
        campaigns: cam,
      });
    } catch (err) {
      dispatch({
        type: "SET_ERROR",
        value: err instanceof Error ? err.message : "Failed to load reports",
      });
    } finally {
      dispatch({ type: "SET_LOADING", value: false });
    }
  }, [range, state.selectedBrandId]);

  // ── AI Report Explainer ────────────────────────────────────────────────────────

  async function handleExplain() {
    dispatch({ type: "SET_EXPLAINING_TAB", value: state.activeTab });
    dispatch({ type: "SET_EXPLANATION", value: null });
    dispatch({ type: "SET_EXPLAIN_ERROR", value: null });

    const tabDataMap: Record<string, unknown[]> = {
      "orders-by-stop": state.ordersByStop,
      "sales-by-product": state.salesByProduct,
      "fulfillment": state.fulfillment,
      "pickup-status": state.pickupStatus,
      "contact-growth": state.contactGrowth,
      "campaigns": state.campaigns,
    };

    const data = tabDataMap[state.activeTab] ?? [];

    try {
      const res = await fetch("/api/ai/report-explainer", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          reportType: state.activeTab,
          dateRange: range,
          brandId: brandId ?? state.selectedBrandId,
          reportData: data,
        }),
      });
      const result = await res.json();
      if (!res.ok) throw new Error(result.error ?? "Analysis failed");
      dispatch({ type: "SET_EXPLANATION", value: result });
    } catch (err) {
      dispatch({
        type: "SET_EXPLAIN_ERROR",
        value: err instanceof Error ? err.message : "Analysis failed",
      });
    } finally {
      dispatch({ type: "SET_EXPLAINING_TAB", value: null });
    }
  }

  // Close explanation panel
  function closeExplanation() {
    dispatch({ type: "SET_EXPLANATION", value: null });
    dispatch({ type: "SET_EXPLAIN_ERROR", value: null });
  }

  // Auto-fetch when range or brand changes. The fetchAll call is wrapped in
  // an async IIFE so the effect body does not call setState synchronously
  // (avoids the cascading-renders ESLint rule).
  useEffect(() => {
    void (async () => {
      await fetchAll();
    })();
  }, [fetchAll]);

  return (
    <div className="space-y-6">
      {state.error && (
        <div className="rounded-xl bg-red-900/30 border border-red-200 px-4 py-3 text-sm text-red-400">
          {state.error}
        </div>
      )}

      <FiltersSection
        preset={state.preset}
        customStart={state.customStart}
        customEnd={state.customEnd}
        selectedBrandId={state.selectedBrandId}
        loading={state.loading}
        isPlatformAdmin={isPlatformAdmin}
        brands={brands}
        range={range}
        currentYear={state.currentYear}
        onSetPreset={(v) => dispatch({ type: "SET_PRESET", value: v })}
        onSetCustomStart={(v) => dispatch({ type: "SET_CUSTOM_START", value: v })}
        onSetCustomEnd={(v) => dispatch({ type: "SET_CUSTOM_END", value: v })}
        onSetSelectedBrandId={(v) => dispatch({ type: "SET_SELECTED_BRAND_ID", value: v })}
        onFetch={fetchAll}
      />

      <AdminFilterTabs
        activeTab={state.activeTab}
        onTabChange={(v) => dispatch({ type: "SET_ACTIVE_TAB", value: v })}
        tabs={TABS}
        size="md"
        showCounts={false}
      />

      {/* Tab content */}
      {state.activeTab === "overview" && (
        <OverviewTab
          summary={state.summary}
          loading={state.loading}
          range={range}
          selectedBrandId={state.selectedBrandId}
          brandNameLookup={(id) => brands.find((b) => b.id === id)?.name ?? id}
        />
      )}

      {state.activeTab === "orders-by-stop" && (
        <OrdersByStopTab
          rows={state.ordersByStop}
          range={range}
          explaining={state.explainingTab === "orders-by-stop"}
          onExplain={handleExplain}
        />
      )}

      {state.activeTab === "sales-by-product" && (
        <SalesByProductTab
          rows={state.salesByProduct}
          range={range}
          explaining={state.explainingTab === "sales-by-product"}
          onExplain={handleExplain}
        />
      )}

      {state.activeTab === "fulfillment" && (
        <FulfillmentTab
          rows={state.fulfillment}
          range={range}
          explaining={state.explainingTab === "fulfillment"}
          onExplain={handleExplain}
        />
      )}

      {state.activeTab === "pickup-status" && (
        <PickupStatusTab
          rows={state.pickupStatus}
          range={range}
          explaining={state.explainingTab === "pickup-status"}
          onExplain={handleExplain}
        />
      )}

      {state.activeTab === "contact-growth" && (
        <ContactGrowthTab
          rows={state.contactGrowth}
          range={range}
          explaining={state.explainingTab === "contact-growth"}
          onExplain={handleExplain}
        />
      )}

      {state.activeTab === "campaigns" && (
        <CampaignsTab
          rows={state.campaigns}
          range={range}
          explaining={state.explainingTab === "campaigns"}
          onExplain={handleExplain}
        />
      )}

      {/* AI Explanation Panel */}
      {state.explanation && (
        <ExplanationPanel
          explanation={state.explanation}
          activeTab={state.activeTab}
          onClose={closeExplanation}
        />
      )}

      {state.explainError && (
        <div className="rounded-xl bg-red-900/30 border border-red-200 px-4 py-3 text-sm text-red-400">
          {state.explainError}
        </div>
      )}
    </div>
  );
}

// ── FiltersSection subcomponent ─────────────────────────────────────────────

function FiltersSection({
  preset,
  customStart,
  customEnd,
  selectedBrandId,
  loading,
  isPlatformAdmin,
  brands,
  range,
  currentYear,
  onSetPreset,
  onSetCustomStart,
  onSetCustomEnd,
  onSetSelectedBrandId,
  onFetch,
}: {
  preset: DatePreset;
  customStart: string;
  customEnd: string;
  selectedBrandId: string;
  loading: boolean;
  isPlatformAdmin: boolean;
  brands: { id: string; name: string }[];
  range: DateRange;
  currentYear: number;
  onSetPreset: (v: DatePreset) => void;
  onSetCustomStart: (v: string) => void;
  onSetCustomEnd: (v: string) => void;
  onSetSelectedBrandId: (v: string) => void;
  onFetch: () => void;
}) {
  return (
    <div className="flex flex-wrap items-center gap-3 rounded-xl border border-[var(--admin-border)] bg-[var(--admin-card-bg)] px-5 py-4">
      {/* Date preset */}
      <div className="flex gap-1.5">
        {(["week", "month", "quarter", "this_year", "custom"] as DatePreset[]).map((p) => (
          <AdminButton
            key={p}
            onClick={() => onSetPreset(p)}
            variant={preset === p ? "primary" : "secondary"}
            size="sm"
          >
            {p === "week" ? "This Week" : p === "month" ? "This Month" : p === "quarter" ? "This Quarter" : p === "this_year" ? "This Year" : "Custom"}
          </AdminButton>
        ))}
      </div>

      {/* Custom date inputs */}
      {preset === "custom" && (
        <div className="flex gap-2 items-center">
          <input aria-label="Date"
            type="date"
            value={customStart}
            onChange={(e) => onSetCustomStart(e.target.value)}
            className="rounded-lg border border-zinc-600 px-3 py-1.5 text-xs"
          />
          <span className="text-slate-400 text-xs">to</span>
          <input aria-label="Date"
            type="date"
            value={customEnd}
            onChange={(e) => onSetCustomEnd(e.target.value)}
            className="rounded-lg border border-zinc-600 px-3 py-1.5 text-xs"
          />
        </div>
      )}

      {/* Brand filter (platform_admin only) */}
      {isPlatformAdmin && (
        <select aria-label="Select"
          value={selectedBrandId}
          onChange={(e) => onSetSelectedBrandId(e.target.value)}
          className="rounded-lg border border-zinc-600 px-3 py-1.5 text-xs"
        >
          <option value="">All Brands</option>
          {brands.map((b) => (
            <option key={b.id} value={b.id}>{b.name}</option>
          ))}
        </select>
      )}

      <AdminButton
        onClick={onFetch}
        disabled={loading}
        variant="primary"
        size="sm"
        isLoading={loading}
      >
        Refresh
      </AdminButton>

      <span className="ml-auto text-sm font-medium text-zinc-500">
        {preset === "quarter" ? quarterLabel(range.start) :
         preset === "this_year" ? `${currentYear} YTD` :
         preset === "month" ? monthLabel(range.start) :
         preset === "custom" ? `${range.start} → ${range.end}` :
         formatDateRange(range.start, range.end)}
      </span>
    </div>
  );
}

// ── OverviewTab subcomponent ────────────────────────────────────────────────

function OverviewTab({
  summary,
  loading,
  range,
  selectedBrandId,
  brandNameLookup,
}: {
  summary: ReportsSummary | null;
  loading: boolean;
  range: DateRange;
  selectedBrandId: string;
  brandNameLookup: (id: string) => string;
}) {
  if (summary) {
    return (
      <div className="space-y-4">
        <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
          <SummaryCard label="Gross Sales" value={summary.gross_sales} prefix="$" />
          <SummaryCard label="Total Orders" value={summary.total_orders} />
          <SummaryCard label="Avg Order Value" value={summary.avg_order_value} prefix="$" />
          <SummaryCard label="Contacts Added" value={summary.contacts_added} />
          <SummaryCard label="Pickup Orders" value={summary.pickup_orders} />
          <SummaryCard label="Shipping Orders" value={summary.shipping_orders} />
          <SummaryCard label="Pending Pickups" value={summary.pending_pickups} />
          <SummaryCard label="Completed Pickups" value={summary.completed_pickups} />
          <SummaryCard label="Campaigns Sent" value={summary.campaigns_sent} />
          <SummaryCard label="Messages Logged" value={summary.messages_logged} />
        </div>
        <p className="text-xs text-slate-400">
          {formatDateRange(range.start, range.end)}
          {selectedBrandId ? ` · Brand: ${brandNameLookup(selectedBrandId)}` : " · All Brands"}
        </p>
      </div>
    );
  }

  if (!loading) {
    return (
      <div className="rounded-xl border border-zinc-800 bg-zinc-900 px-6 py-12 text-center text-slate-400">
        Click Refresh to load summary data
      </div>
    );
  }

  return null;
}

// ── OrdersByStopTab subcomponent ────────────────────────────────────────────

function OrdersByStopTab({
  rows,
  range,
  explaining,
  onExplain,
}: {
  rows: OrderByStop[];
  range: DateRange;
  explaining: boolean;
  onExplain: () => void;
}) {
  return (
    <div className="space-y-3">
      <div className="flex items-center justify-between">
        <h3 className="text-sm font-semibold text-zinc-300">Orders by Stop</h3>
        <div className="flex gap-2">
          <ExplainBtn onClick={onExplain} loading={explaining} />
          {rows.length > 0 && (
            <ExportBtn
              onClick={() =>
                handleExportCSV(
                  () => exportOrdersByStop(rows),
                  `orders-by-stop-${range.start}.csv`
                )
              }
            />
          )}
        </div>
      </div>
      <div className="rounded-xl border border-zinc-800 bg-zinc-900 overflow-hidden">
        <ReportTable
          headers={["Stop", "City", "State", "Date", "Orders", "Gross Sales", "Pending", "Completed"]}
          rows={rows}
          renderRow={(row) => {
            const r = row as OrderByStop;
            return (
              <tr key={r.stop_name + r.date} className="border-t border-slate-100 hover:bg-zinc-800">
                <td className="px-3 py-2 font-medium text-zinc-100">{r.stop_name}</td>
                <td className="px-3 py-2 text-zinc-400">{r.city}</td>
                <td className="px-3 py-2 text-zinc-400">{r.state}</td>
                <td className="px-3 py-2 text-zinc-400">{formatDate(r.date)}</td>
                <td className="px-3 py-2 text-right font-medium">{r.order_count}</td>
                <td className="px-3 py-2 text-right">${r.gross_sales.toFixed(2)}</td>
                <td className="px-3 py-2 text-right text-amber-400">{r.pending_count}</td>
                <td className="px-3 py-2 text-right text-green-600">{r.completed_count}</td>
              </tr>
            );
          }}
        />
      </div>
    </div>
  );
}

// ── SalesByProductTab subcomponent ───────────────────────────────────────────

function SalesByProductTab({
  rows,
  range,
  explaining,
  onExplain,
}: {
  rows: SalesByProduct[];
  range: DateRange;
  explaining: boolean;
  onExplain: () => void;
}) {
  return (
    <div className="space-y-3">
      <div className="flex items-center justify-between">
        <h3 className="text-sm font-semibold text-zinc-300">Sales by Product</h3>
        <div className="flex gap-2">
          <ExplainBtn onClick={onExplain} loading={explaining} />
          {rows.length > 0 && (
            <ExportBtn
              onClick={() =>
                handleExportCSV(
                  () => exportSalesByProduct(rows),
                  `sales-by-product-${range.start}.csv`
                )
              }
            />
          )}
        </div>
      </div>
      <div className="rounded-xl border border-zinc-800 bg-zinc-900 overflow-hidden">
        <ReportTable
          headers={["Product", "Units Sold", "Gross Revenue", "Avg Price"]}
          rows={rows}
          renderRow={(row) => {
            const r = row as SalesByProduct;
            return (
              <tr key={r.product_name} className="border-t border-slate-100 hover:bg-zinc-800">
                <td className="px-3 py-2 font-medium text-zinc-100">{r.product_name}</td>
                <td className="px-3 py-2 text-right">{r.units_sold}</td>
                <td className="px-3 py-2 text-right font-medium">${r.gross_revenue.toFixed(2)}</td>
                <td className="px-3 py-2 text-right text-zinc-500">${r.avg_price}</td>
              </tr>
            );
          }}
        />
      </div>
    </div>
  );
}

// ── FulfillmentTab subcomponent ─────────────────────────────────────────────

function FulfillmentTab({
  rows,
  range,
  explaining,
  onExplain,
}: {
  rows: FulfillmentRow[];
  range: DateRange;
  explaining: boolean;
  onExplain: () => void;
}) {
  return (
    <div className="space-y-3">
      <div className="flex items-center justify-between">
        <h3 className="text-sm font-semibold text-zinc-300">Fulfillment Breakdown</h3>
        <div className="flex gap-2">
          <ExplainBtn onClick={onExplain} loading={explaining} />
          {rows.length > 0 && (
            <ExportBtn
              onClick={() =>
                handleExportCSV(
                  () => exportFulfillment(rows),
                  `fulfillment-${range.start}.csv`
                )
              }
            />
          )}
        </div>
      </div>
      <div className="rounded-xl border border-zinc-800 bg-zinc-900 overflow-hidden">
        <ReportTable
          headers={["Fulfillment Type", "Order Count", "Revenue", "% of Total"]}
          rows={rows}
          renderRow={(row) => {
            const r = row as FulfillmentRow;
            return (
              <tr key={r.fulfillment_type} className="border-t border-slate-100 hover:bg-zinc-800">
                <td className="px-3 py-2">
                  <span className={`rounded-full px-2 py-0.5 text-xs font-medium ${
                    r.fulfillment_type === "pickup" ? "bg-blue-900/40 text-blue-700" :
                    r.fulfillment_type === "shipping" ? "bg-purple-100 text-purple-700" :
                    "bg-zinc-950 text-zinc-300"
                  }`}>{r.fulfillment_type}</span>
                </td>
                <td className="px-3 py-2 text-right">{r.order_count}</td>
                <td className="px-3 py-2 text-right font-medium">${r.revenue.toFixed(2)}</td>
                <td className="px-3 py-2 text-right text-zinc-500">{r.pct_of_total}%</td>
              </tr>
            );
          }}
        />
      </div>
    </div>
  );
}

// ── PickupStatusTab subcomponent ────────────────────────────────────────────

function PickupStatusTab({
  rows,
  range,
  explaining,
  onExplain,
}: {
  rows: PickupStatusByStop[];
  range: DateRange;
  explaining: boolean;
  onExplain: () => void;
}) {
  return (
    <div className="space-y-3">
      <div className="flex items-center justify-between">
        <h3 className="text-sm font-semibold text-zinc-300">Pickup Status by Stop</h3>
        <div className="flex gap-2">
          <ExplainBtn onClick={onExplain} loading={explaining} />
          {rows.length > 0 && (
            <ExportBtn
              onClick={() =>
                handleExportCSV(
                  () => exportPickupStatus(rows),
                  `pickup-status-${range.start}.csv`
                )
              }
            />
          )}
        </div>
      </div>
      <div className="rounded-xl border border-zinc-800 bg-zinc-900 overflow-hidden">
        <ReportTable
          headers={["Stop", "City", "Date", "Total Orders", "Pending", "Completed", "Canceled"]}
          rows={rows}
          renderRow={(row) => {
            const r = row as PickupStatusByStop;
            return (
              <tr key={r.stop_name + r.date} className="border-t border-slate-100 hover:bg-zinc-800">
                <td className="px-3 py-2 font-medium text-zinc-100">{r.stop_name}</td>
                <td className="px-3 py-2 text-zinc-400">{r.city}</td>
                <td className="px-3 py-2 text-zinc-400">{formatDate(r.date)}</td>
                <td className="px-3 py-2 text-right font-medium">{r.total_orders}</td>
                <td className="px-3 py-2 text-right text-amber-400">{r.pending}</td>
                <td className="px-3 py-2 text-right text-green-600">{r.completed}</td>
                <td className="px-3 py-2 text-right text-slate-400">{r.canceled}</td>
              </tr>
            );
          }}
        />
      </div>
    </div>
  );
}

// ── ContactGrowthTab subcomponent ───────────────────────────────────────────

function ContactGrowthTab({
  rows,
  range,
  explaining,
  onExplain,
}: {
  rows: ContactGrowthRow[];
  range: DateRange;
  explaining: boolean;
  onExplain: () => void;
}) {
  return (
    <div className="space-y-3">
      <div className="flex items-center justify-between">
        <h3 className="text-sm font-semibold text-zinc-300">Contact Growth</h3>
        <div className="flex gap-2">
          <ExplainBtn onClick={onExplain} loading={explaining} />
          {rows.length > 0 && (
            <ExportBtn
              onClick={() =>
                handleExportCSV(
                  () => exportContactGrowth(rows),
                  `contact-growth-${range.start}.csv`
                )
              }
            />
          )}
        </div>
      </div>
      <div className="rounded-xl border border-zinc-800 bg-zinc-900 overflow-hidden">
        <ReportTable
          headers={["Date", "New Contacts", "Imports", "Total"]}
          rows={rows}
          renderRow={(row) => {
            const r = row as ContactGrowthRow;
            return (
              <tr key={r.date} className="border-t border-slate-100 hover:bg-zinc-800">
                <td className="px-3 py-2 text-zinc-300">{r.date}</td>
                <td className="px-3 py-2 text-right">{r.new_contacts}</td>
                <td className="px-3 py-2 text-right text-blue-400">{r.imports}</td>
                <td className="px-3 py-2 text-right font-medium">{r.total}</td>
              </tr>
            );
          }}
        />
      </div>
    </div>
  );
}

// ── CampaignsTab subcomponent ───────────────────────────────────────────────

function CampaignsTab({
  rows,
  range,
  explaining,
  onExplain,
}: {
  rows: CampaignActivityRow[];
  range: DateRange;
  explaining: boolean;
  onExplain: () => void;
}) {
  return (
    <div className="space-y-3">
      <div className="flex items-center justify-between">
        <h3 className="text-sm font-semibold text-zinc-300">Campaign Activity</h3>
        <div className="flex gap-2">
          <ExplainBtn onClick={onExplain} loading={explaining} />
          {rows.length > 0 && (
            <ExportBtn
              onClick={() =>
                handleExportCSV(
                  () => exportCampaignActivity(rows),
                  `campaigns-${range.start}.csv`
                )
              }
            />
          )}
        </div>
      </div>
      <div className="rounded-xl border border-zinc-800 bg-zinc-900 overflow-hidden">
        <ReportTable
          headers={["Campaign", "Status", "Type", "Sent At", "Messages Logged"]}
          rows={rows}
          renderRow={(row) => {
            const r = row as CampaignActivityRow;
            return (
              <tr key={r.campaign_name} className="border-t border-slate-100 hover:bg-zinc-800">
                <td className="px-3 py-2 font-medium text-zinc-100">{r.campaign_name}</td>
                <td className="px-3 py-2">
                  <span className={`rounded-full px-2 py-0.5 text-xs font-medium ${
                    r.status === "sent" ? "bg-green-900/40 text-green-400" :
                    r.status === "draft" ? "bg-zinc-950 text-zinc-400" :
                    "bg-amber-100 text-amber-700"
                  }`}>{r.status}</span>
                </td>
                <td className="px-3 py-2 text-zinc-500 text-xs">{r.campaign_type}</td>
                <td className="px-3 py-2 text-zinc-500 text-xs">{r.sent_at ?? "—"}</td>
                <td className="px-3 py-2 text-right">{r.messages_logged}</td>
              </tr>
            );
          }}
        />
      </div>
    </div>
  );
}

// ── ExplanationPanel subcomponent ───────────────────────────────────────────

function ExplanationPanel({
  explanation,
  activeTab,
  onClose,
}: {
  explanation: { summary: string; keyInsights: string[]; suggestedActions: string[] };
  activeTab: string;
  onClose: () => void;
}) {
  return (
    <div className="rounded-2xl border border-violet-200 bg-gradient-to-br from-violet-50 to-white shadow-lg overflow-hidden">
      <div className="bg-violet-600 px-5 py-3 flex items-center justify-between">
        <div className="flex items-center gap-2">
          <span className="text-lg">🤖</span>
          <h3 className="font-semibold text-white">AI Report Analysis</h3>
          <span className="text-xs text-violet-200 ml-1">· {activeTab.replace("-", " ")}</span>
        </div>
        <button type="button" onClick={onClose} className="text-violet-200 hover:text-white p-1" aria-label="Close">
          <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
          </svg>
        </button>
      </div>
      <div className="p-5 space-y-4">
        <div className="rounded-xl bg-zinc-900 border border-violet-100 p-4">
          <p className="text-xs font-semibold text-violet-500 uppercase tracking-wider mb-2">Summary</p>
          <p className="text-sm text-zinc-300 leading-relaxed">{explanation.summary}</p>
        </div>
        <div className="rounded-xl bg-zinc-900 border border-violet-100 p-4">
          <p className="text-xs font-semibold text-violet-500 uppercase tracking-wider mb-2">Key Insights</p>
          <ul className="space-y-2">
            {explanation.keyInsights.map((insight, i) => (
              <li key={`${insight}-${i}`} className="flex items-start gap-2 text-sm text-zinc-300">
                <span className="text-violet-500 mt-0.5 flex-shrink-0">→</span>
                <span>{insight}</span>
              </li>
            ))}
          </ul>
        </div>
        <div className="rounded-xl bg-zinc-900 border border-violet-100 p-4">
          <p className="text-xs font-semibold text-green-600 uppercase tracking-wider mb-2">Suggested Actions</p>
          <ul className="space-y-2">
            {explanation.suggestedActions.map((action, i) => (
              <li key={`${action}-${i}`} className="flex items-start gap-2 text-sm text-zinc-300">
                <span className="text-green-500 mt-0.5 flex-shrink-0">✓</span>
                <span>{action}</span>
              </li>
            ))}
          </ul>
        </div>
        <div className="rounded-lg bg-amber-900/30 border border-amber-200 p-3 text-xs text-amber-700">
          ⚠️ AI-generated suggestions — review before use. Not a substitute for business judgment.
        </div>
      </div>
    </div>
  );
}
