import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
import type { DateRange } from "react-day-picker";
import { Search, Download, Printer, Calendar as CalendarIcon, BarChart3, LineChart, ArrowUpRight, RefreshCw, FileText } from "lucide-react";
import { Button } from "../ui/button";
import { Input } from "../ui/input";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "../ui/table";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "../ui/select";
import { Popover, PopoverContent, PopoverTrigger } from "../ui/popover";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "../ui/card";
import { Calendar } from "../ui/calendar";
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, Line, LineChart as RechartsLineChart } from "recharts";
import { toast } from "sonner";
import { cn } from "../ui/utils";
import { skipCountForPage } from "../../lib/paginationQuery";
import { getLocations } from "../../services/locationService";
import { getPartners } from "../../services/partnerService";
import { getGroups } from "../../services/groupService";
import {
  exportPrintLogExcel,
  getLabelReport,
  getReportsPrintLogList,
} from "../../services/reportsService";
import type { LocationDto } from "../../types/location";
import type { PartnerListItem } from "../../types/partner";
import type { GroupListItem } from "../../types/group";
import type { LabelReportData, ReportsPrintLogListItem } from "../../types/reports";
import { ApiError } from "../../lib/apiClient";
import { BACKEND_EMPTY_DISPLAY } from "../../lib/emptyDisplay";
import { useCategoryScopeAuth } from "../../hooks/useCategoryScopeAuth";
import {
  Pagination,
  PaginationContent,
  PaginationItem,
  PaginationLink,
  PaginationNext,
  PaginationPrevious,
} from "../ui/pagination";

const ALL = "all" as const;

function defaultDateRange(): { start: string; end: string } {
  const end = new Date();
  const start = new Date(end);
  start.setDate(start.getDate() - 29);
  return {
    start: start.toISOString().slice(0, 10),
    end: end.toISOString().slice(0, 10),
  };
}

function parseIsoDate(value: string): Date | undefined {
  const s = (value ?? "").trim();
  if (!/^\d{4}-\d{2}-\d{2}$/.test(s)) return undefined;
  const d = new Date(`${s}T00:00:00`);
  if (Number.isNaN(d.getTime())) return undefined;
  return d;
}

function formatIsoDate(value: Date): string {
  const y = value.getFullYear();
  const m = String(value.getMonth() + 1).padStart(2, "0");
  const d = String(value.getDate()).padStart(2, "0");
  return `${y}-${m}-${d}`;
}

function formatPrintedAt(raw: string): string {
  const s = (raw ?? "").trim();
  if (!s) return "None";
  const d = new Date(s);
  if (Number.isNaN(d.getTime())) return s;
  const mm = String(d.getMonth() + 1).padStart(2, "0");
  const dd = String(d.getDate()).padStart(2, "0");
  const yy = String(d.getFullYear()).slice(-2);
  const hh = String(d.getHours()).padStart(2, "0");
  const min = String(d.getMinutes()).padStart(2, "0");
  return `${mm}/${dd}/${yy} ${hh}:${min}`;
}

function tryParseOffsetPayload(raw: string): { amount: number; unit: string } | null {
  const s = raw.trim();
  if (!s.startsWith("{")) return null;
  try {
    const o = JSON.parse(s) as Record<string, unknown>;
    const unit = String(o.unit ?? o.Unit ?? "Days").trim() || "Days";
    const valRaw = o.value ?? o.Value;
    const amount = Number(valRaw);
    if (!Number.isFinite(amount)) return null;
    return { amount: Math.round(amount), unit };
  } catch {
    return null;
  }
}

function applyOffsetAnchor(base: Date, amount: number, unit: string): Date {
  const u = unit.trim().toLowerCase();
  const next = new Date(base.getTime());
  if (u === "hour" || u === "hours") next.setHours(next.getHours() + amount);
  else if (u === "minute" || u === "minutes") next.setMinutes(next.getMinutes() + amount);
  else next.setDate(next.getDate() + amount);
  return next;
}

function resolveExpiryAnchor(printedAtRaw?: string): Date {
  const anchorRaw = (printedAtRaw ?? "").trim();
  if (anchorRaw && anchorRaw !== BACKEND_EMPTY_DISPLAY) {
    const partial = anchorRaw.match(/^(\d{1,2})\/(\d{1,2})(?:\/(\d{2,4}))?$/);
    if (partial) {
      const month = Number(partial[1]);
      const day = Number(partial[2]);
      const yearToken = partial[3];
      const year = yearToken
        ? yearToken.length === 2
          ? 2000 + Number(yearToken)
          : Number(yearToken)
        : new Date().getFullYear();
      const dt = new Date(year, month - 1, day, 0, 0, 0, 0);
      if (!Number.isNaN(dt.getTime())) return dt;
    }
    const parsed = new Date(anchorRaw);
    if (!Number.isNaN(parsed.getTime())) return parsed;
  }
  return new Date();
}

function formatExpiryDateOnly(d: Date): string {
  const mm = String(d.getMonth() + 1).padStart(2, "0");
  const dd = String(d.getDate()).padStart(2, "0");
  const yy = String(d.getFullYear()).slice(-2);
  return `${mm}/${dd}/${yy}`;
}

/**
 * Expiration 列：有真实到期时分则 MM/DD/YY HH:mm；纯日期不伪造 00:00。
 * 兼容后端已算好的日期+时分、纯日期、offset JSON。
 */
function formatExpiryDateText(raw: string, printedAtRaw?: string): string {
  const s = (raw ?? "").trim();
  if (!s || s === BACKEND_EMPTY_DISPLAY) return "None";

  // 后端已输出 MM/dd/yy HH:mm：直接规范化透传
  const backendDateTime = s.match(/^(\d{1,2})\/(\d{1,2})\/(\d{2,4})\s+(\d{1,2}:\d{2})$/);
  if (backendDateTime) {
    const mm = String(Number(backendDateTime[1])).padStart(2, "0");
    const dd = String(Number(backendDateTime[2])).padStart(2, "0");
    const yyRaw = backendDateTime[3];
    const yy = yyRaw.length === 2 ? yyRaw : String(Number(yyRaw)).slice(-2);
    const [hhRaw, minRaw] = backendDateTime[4].split(":");
    const hh = String(Number(hhRaw)).padStart(2, "0");
    const min = String(minRaw).padStart(2, "0");
    return `${mm}/${dd}/${yy} ${hh}:${min}`;
  }

  const anchor = resolveExpiryAnchor(printedAtRaw);
  const anchorOk = !Number.isNaN(anchor.getTime());

  const offset = tryParseOffsetPayload(s);
  if (offset && anchorOk) {
    return formatPrintedAt(applyOffsetAnchor(anchor, offset.amount, offset.unit).toISOString());
  }

  // 纯日期 MM/DD/YY：原样日期展示（不补 00:00）
  const dateOnly = s.match(/^(\d{1,2})\/(\d{1,2})\/(\d{2,4})$/);
  if (dateOnly) {
    const mm = String(Number(dateOnly[1])).padStart(2, "0");
    const dd = String(Number(dateOnly[2])).padStart(2, "0");
    const yyRaw = dateOnly[3];
    const yy = yyRaw.length === 2 ? yyRaw : String(Number(yyRaw)).slice(-2);
    return `${mm}/${dd}/${yy}`;
  }

  const partial = s.match(/^(\d{1,2})\/(\d{1,2})(?:\/(\d{2,4}))?(?:\s+(\d{1,2}:\d{2}))?$/);
  if (partial) {
    const month = Number(partial[1]);
    const day = Number(partial[2]);
    const yearToken = partial[3];
    const year = yearToken
      ? yearToken.length === 2
        ? 2000 + Number(yearToken)
        : Number(yearToken)
      : anchor.getFullYear();
    const dt = new Date(year, month - 1, day, 0, 0, 0, 0);
    if (partial[4]) {
      const [hh, mm] = partial[4].split(":").map((x) => Number(x));
      if (Number.isFinite(hh)) dt.setHours(hh);
      if (Number.isFinite(mm)) dt.setMinutes(mm);
      return formatPrintedAt(dt.toISOString());
    }
    return formatExpiryDateOnly(dt);
  }

  const parsed = new Date(s);
  if (!Number.isNaN(parsed.getTime()) && /[T ]\d{1,2}:\d{2}/.test(s)) {
    return formatPrintedAt(parsed.toISOString());
  }

  return s;
}

function toDisplay(v: string | null | undefined): string {
  const s = (v ?? "").trim();
  if (!s || s === BACKEND_EMPTY_DISPLAY) return "None";
  return s;
}

function formatPct(n: number): string {
  if (!Number.isFinite(n)) return "0%";
  const sign = n > 0 ? "+" : "";
  return `${sign}${n.toFixed(1)}%`;
}

function formatTrendLabel(iso: string): string {
  const s = (iso ?? "").trim();
  if (!s) return "";
  const d = new Date(s);
  if (Number.isNaN(d.getTime())) return s.length > 10 ? s.slice(0, 10) : s;
  return d.toLocaleDateString("en-US", { month: "numeric", day: "numeric" });
}

/** Reports 筛选：单弹层 + range 日历，避免双日历布局问题 */
function PeriodRangePicker({
  startDate,
  endDate,
  onRangeChange,
}: {
  startDate: string;
  endDate: string;
  onRangeChange: (start: string, end: string) => void;
}) {
  const [open, setOpen] = useState(false);
  const selectedRange: DateRange | undefined = useMemo(() => {
    const from = parseIsoDate(startDate);
    const to = parseIsoDate(endDate);
    if (from && to) return { from, to };
    if (from) return { from, to: undefined };
    return undefined;
  }, [startDate, endDate]);

  const label = `${startDate || "YYYY-MM-DD"}  —  ${endDate || "YYYY-MM-DD"}`;

  return (
    <div className="flex items-center gap-2 shrink-0" lang="en-US">
      <span className="text-sm font-medium font-sans text-gray-900">Period Search:</span>
      <Popover open={open} onOpenChange={setOpen}>
        <PopoverTrigger asChild>
          <Button
            type="button"
            variant="outline"
            className="h-10 min-w-[17rem] justify-start gap-2 rounded-md border border-gray-300 bg-white px-3 text-sm font-medium font-sans text-gray-900 hover:bg-gray-50"
          >
            <CalendarIcon className="h-4 w-4 shrink-0 text-gray-500" aria-hidden />
            {label}
          </Button>
        </PopoverTrigger>
        <PopoverContent className="w-auto p-0" align="start">
          <Calendar
            mode="range"
            numberOfMonths={1}
            defaultMonth={parseIsoDate(startDate) ?? parseIsoDate(endDate) ?? new Date()}
            selected={selectedRange}
            onSelect={(range) => {
              if (!range?.from) return;
              const s = formatIsoDate(range.from);
              const e = range.to ? formatIsoDate(range.to) : s;
              onRangeChange(s, e);
              if (range.from && range.to) setOpen(false);
            }}
            initialFocus
          />
        </PopoverContent>
      </Popover>
    </div>
  );
}

/** Print Log 列表行统一字体 */
const PRINT_LOG_CELL = "border-r text-sm font-normal font-sans text-gray-900";
const PRINT_LOG_HEAD = "text-sm font-semibold font-sans text-gray-900 border-r";

function templateCell(template: string) {
  const t = (template ?? "").trim();
  if (!t) return "None";
  if (t.endsWith(" !!!")) {
    return (
      <>
        {t.slice(0, -4)}
        <span className="text-red-600"> !!!</span>
      </>
    );
  }
  return t;
}

const EMPTY_LABEL_REPORT: LabelReportData = {
  summary: {
    totalLabelsPrinted: 0,
    totalLabelsPrintedPrevPeriod: 0,
    totalLabelsPrintedChangeRate: 0,
    hottestCategoryName: "None",
    hottestCategoryCount: 0,
    topProductName: "None",
    topProductCount: 0,
    avgDailyPrints: 0,
    avgDailyPrintsChangeRate: 0,
  },
  labelsByCategory: [],
  printVolumeTrend: [],
  mostUsedProducts: [],
};

export type ReportsViewProps = {
  layoutReportsOpenKey?: number;
  layoutReportsTargetTab?: "print-log" | "label-report";
};

export function ReportsView({
  layoutReportsOpenKey = 0,
  layoutReportsTargetTab = "label-report",
}: ReportsViewProps = {}) {
  const scopeAuth = useCategoryScopeAuth();
  const [activeTab, setActiveTab] = useState<"print-log" | "label-report">("print-log");
  const lastAppliedLayoutKeyRef = useRef(0);

  const [partners, setPartners] = useState<PartnerListItem[]>([]);
  const [groups, setGroups] = useState<GroupListItem[]>([]);
  const [locations, setLocations] = useState<LocationDto[]>([]);

  const [partnerId, setPartnerId] = useState<string>(ALL);
  const [groupId, setGroupId] = useState<string>(ALL);
  const [locationId, setLocationId] = useState<string>(ALL);

  const { start: defaultStart, end: defaultEnd } = defaultDateRange();
  const [startDate, setStartDate] = useState<string>(defaultStart);
  const [endDate, setEndDate] = useState<string>(defaultEnd);
  const [keyword, setKeyword] = useState("");

  const [debouncedKeyword, setDebouncedKeyword] = useState("");
  const keywordTimerRef = useRef<number | null>(null);

  const [printRows, setPrintRows] = useState<ReportsPrintLogListItem[]>([]);
  const [printTotal, setPrintTotal] = useState(0);
  const [printLoading, setPrintLoading] = useState(false);
  const [pageIndex, setPageIndex] = useState(1);
  const [pageSize] = useState(10);

  const [labelData, setLabelData] = useState<LabelReportData | null>(null);
  const [labelLoading, setLabelLoading] = useState(false);
  const [exporting, setExporting] = useState(false);
  const [filterMetaLoading, setFilterMetaLoading] = useState(true);

  const printAbortRef = useRef<AbortController | null>(null);
  const labelAbortRef = useRef<AbortController | null>(null);

  useEffect(() => {
    if (keywordTimerRef.current) window.clearTimeout(keywordTimerRef.current);
    keywordTimerRef.current = window.setTimeout(() => setDebouncedKeyword(keyword.trim()), 300);
    return () => {
      if (keywordTimerRef.current) window.clearTimeout(keywordTimerRef.current);
    };
  }, [keyword]);

  useEffect(() => {
    if (layoutReportsOpenKey > 0 && layoutReportsOpenKey > lastAppliedLayoutKeyRef.current) {
      lastAppliedLayoutKeyRef.current = layoutReportsOpenKey;
      setActiveTab(layoutReportsTargetTab);
    }
  }, [layoutReportsOpenKey, layoutReportsTargetTab]);

  const totalPages = Math.max(1, Math.ceil(printTotal / pageSize));

  const effectivePartnerId = useMemo(() => {
    if (scopeAuth.requireCompanySelection) return partnerId;
    const fixed = scopeAuth.fixedPartnerId.trim();
    return fixed || partnerId;
  }, [scopeAuth.requireCompanySelection, scopeAuth.fixedPartnerId, partnerId]);

  const partnerNameForQuery = useCallback((): string | undefined => {
    if (effectivePartnerId === ALL) return undefined;
    const p = partners.find((x) => x.id === effectivePartnerId);
    return p?.partnerName?.trim() || undefined;
  }, [effectivePartnerId, partners]);

  const groupNameForQuery = useCallback((): string | undefined => {
    if (groupId === ALL) return undefined;
    const g = groups.find((x) => x.id === groupId);
    return g?.groupName?.trim() || undefined;
  }, [groupId, groups]);

  const buildReportFilters = useCallback(
    () => ({
      partnerId: effectivePartnerId === ALL ? undefined : effectivePartnerId,
      groupId: groupId === ALL ? undefined : groupId,
      locationId: locationId === ALL ? undefined : locationId,
      startDate: startDate.trim() || undefined,
      endDate: endDate.trim() || undefined,
      keyword: debouncedKeyword || undefined,
    }),
    [debouncedKeyword, effectivePartnerId, endDate, groupId, locationId, startDate]
  );

  useEffect(() => {
    setPageIndex(1);
  }, [debouncedKeyword, partnerId, groupId, locationId, startDate, endDate, activeTab, pageSize]);

  useEffect(() => {
    if (scopeAuth.requireCompanySelection) return;
    const pid = scopeAuth.fixedPartnerId.trim();
    if (pid) setPartnerId(pid);
  }, [scopeAuth.requireCompanySelection, scopeAuth.fixedPartnerId]);

  useEffect(() => {
    let cancel = false;
    const run = async () => {
      setFilterMetaLoading(true);
      try {
        const tasks: [Promise<void>, Promise<void>] = [
          (async () => {
            if (!scopeAuth.requireCompanySelection) return;
            const pRes = await getPartners({ skipCount: 1, maxResultCount: 500, state: true });
            if (cancel) return;
            setPartners(pRes.items ?? []);
          })(),
          (async () => {
            const gRes = await getGroups({ skipCount: 1, maxResultCount: 500, state: true });
            if (cancel) return;
            setGroups(gRes.items ?? []);
          })(),
        ];
        await Promise.all(tasks);
      } catch (e) {
        if (!cancel) {
          if (scopeAuth.requireCompanySelection) setPartners([]);
          setGroups([]);
          toast.error("Failed to load companies / regions.", {
            description: e instanceof Error ? e.message : "Please try again.",
          });
        }
      } finally {
        if (!cancel) setFilterMetaLoading(false);
      }
    };
    run();
    return () => {
      cancel = true;
    };
  }, [scopeAuth.requireCompanySelection]);

  useEffect(() => {
    let cancel = false;
    const run = async () => {
      try {
        const res = await getLocations({
          skipCount: 1,
          maxResultCount: 2000,
          partner: partnerNameForQuery(),
          groupName: groupNameForQuery(),
          state: true,
        });
        if (cancel) return;
        setLocations(res.items ?? []);
      } catch (e) {
        if (!cancel) {
          setLocations([]);
          toast.error("Failed to load locations.", {
            description: e instanceof Error ? e.message : "Please try again.",
          });
        }
      }
    };
    run();
    return () => {
      cancel = true;
    };
  }, [groupNameForQuery, partnerNameForQuery, effectivePartnerId, groupId]);

  useEffect(() => {
    if (activeTab !== "print-log") return;

    const run = async () => {
      printAbortRef.current?.abort();
      const ac = new AbortController();
      printAbortRef.current = ac;
      setPrintLoading(true);
      const f = buildReportFilters();
      try {
        const res = await getReportsPrintLogList(
          {
            skipCount: skipCountForPage(pageIndex),
            maxResultCount: pageSize,
            sorting: "PrintedAt desc",
            ...f,
          },
          ac.signal
        );
        setPrintRows(res.items ?? []);
        setPrintTotal(res.totalCount ?? 0);
      } catch (e) {
        if (e instanceof Error && e.name === "AbortError") return;
        toast.error("Failed to load print log.", {
          description: e instanceof Error ? e.message : "Please try again.",
        });
        setPrintRows([]);
        setPrintTotal(0);
      } finally {
        if (!ac.signal.aborted) setPrintLoading(false);
      }
    };
    void run();
    return () => printAbortRef.current?.abort();
  }, [activeTab, buildReportFilters, pageIndex, pageSize]);

  useEffect(() => {
    if (activeTab !== "label-report") return;
    const run = async () => {
      labelAbortRef.current?.abort();
      const ac = new AbortController();
      labelAbortRef.current = ac;
      setLabelLoading(true);
      const f = buildReportFilters();
      try {
        const data = await getLabelReport(f, ac.signal);
        setLabelData(data);
      } catch (e) {
        if (e instanceof Error && e.name === "AbortError") return;
        toast.error("Failed to load label report.", {
          description: e instanceof Error ? e.message : "Please try again.",
        });
        setLabelData(EMPTY_LABEL_REPORT);
      } finally {
        if (!ac.signal.aborted) setLabelLoading(false);
      }
    };
    void run();
    return () => labelAbortRef.current?.abort();
  }, [activeTab, buildReportFilters]);

  const onPartnerChange = (v: string) => {
    setPartnerId(v);
    setGroupId(ALL);
    setLocationId(ALL);
  };

  const onGroupChange = (v: string) => {
    setGroupId(v);
    setLocationId(ALL);
  };

  const handleExport = async () => {
    const f = buildReportFilters();
    setExporting(true);
    try {
      await exportPrintLogExcel({
        ...f,
        skipCount: 1,
        maxResultCount: 10,
        sorting: "PrintedAt desc",
      });
      toast.success("Export ready", { description: "The Excel download should start shortly." });
    } catch (e) {
      const msg = e instanceof ApiError ? e.message : e instanceof Error ? e.message : "Please try again.";
      toast.error("Export failed", { description: msg });
    } finally {
      setExporting(false);
    }
  };

  const report = labelData ?? EMPTY_LABEL_REPORT;
  const trendData = (report.printVolumeTrend ?? []).map((p) => ({
    date: formatTrendLabel(p.date),
    count: p.count,
  }));
  const categoryData = (report.labelsByCategory ?? []).map((c) => ({ name: c.name, count: c.count }));

  return (
    <div className="h-full flex flex-col">
      <div className="pb-4">
        <div className="flex flex-wrap items-center gap-3">
          {scopeAuth.requireCompanySelection ? (
            <Select value={partnerId} onValueChange={onPartnerChange} disabled={filterMetaLoading}>
              <SelectTrigger className="w-[140px] h-10 rounded-md border border-gray-300 bg-white font-medium text-gray-900 shrink-0">
                <SelectValue placeholder="Company" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value={ALL}>All companies</SelectItem>
                {partners.map((p) => (
                  <SelectItem key={p.id} value={p.id}>
                    {toDisplay(p.partnerName)}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          ) : null}
          <Select
            value={groupId}
            onValueChange={onGroupChange}
            disabled={filterMetaLoading || scopeAuth.loadingPartner}
          >
            <SelectTrigger className="w-[140px] h-10 rounded-md border border-gray-300 bg-white font-medium text-gray-900 shrink-0">
              <SelectValue placeholder="Region" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value={ALL}>All regions</SelectItem>
              {groups
                .filter((g) => (effectivePartnerId === ALL ? true : g.partnerId === effectivePartnerId))
                .map((g) => (
                  <SelectItem key={g.id} value={g.id}>
                    {toDisplay(g.groupName)}
                  </SelectItem>
                ))}
            </SelectContent>
          </Select>
          <Select
            value={locationId}
            onValueChange={setLocationId}
            disabled={filterMetaLoading || scopeAuth.loadingPartner}
          >
            <SelectTrigger className="w-[160px] h-10 rounded-md border border-gray-300 bg-white font-medium text-gray-900 shrink-0">
              <SelectValue placeholder="Location" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value={ALL}>All locations</SelectItem>
              {locations.map((loc) => (
                <SelectItem key={loc.id} value={loc.id ?? ""}>
                  {toDisplay(loc.locationName) || toDisplay(loc.locationCode)}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
          <PeriodRangePicker
            startDate={startDate}
            endDate={endDate}
            onRangeChange={(start, end) => {
              setStartDate(start);
              setEndDate(end);
            }}
          />
          <div
            className="flex items-center w-64 rounded-md border border-gray-300 bg-white overflow-hidden shrink-0"
            style={{ height: 40 }}
          >
            <Search className="h-4 w-4 text-gray-400 shrink-0 ml-3 pointer-events-none" />
            <Input
              value={keyword}
              onChange={(e) => setKeyword(e.target.value)}
              placeholder="Search Product or Category..."
              className="flex-1 min-w-0 border-0 bg-transparent focus-visible:ring-0 focus-visible:ring-offset-0 py-2 px-2 h-full placeholder:text-gray-500"
            />
          </div>
          <div className="flex-1 min-w-2" />
          {activeTab === "print-log" && (
            <Button
              type="button"
              variant="outline"
              className="h-10 border border-gray-300 rounded-md text-gray-900 bg-white hover:bg-gray-50 gap-2 shrink-0"
              disabled={exporting}
              onClick={() => void handleExport()}
            >
              <Download className="w-4 h-4" /> {exporting ? "Exporting…" : "Export Report"}
            </Button>
          )}
        </div>

        <div className="w-full border-b border-gray-200 mt-4">
          <div className="flex overflow-x-auto w-fit">
            <button
              type="button"
              onClick={() => setActiveTab("print-log")}
              style={
                activeTab === "print-log" ? { borderBottomWidth: 2, borderBottomStyle: "solid", borderBottomColor: "#2563eb" } : undefined
              }
              className={cn(
                "px-4 py-2.5 text-sm font-medium whitespace-nowrap cursor-pointer transition-colors -mb-px border-b-2",
                activeTab === "print-log" ? "text-blue-600" : "border-b-transparent text-gray-600 hover:text-gray-800"
              )}
            >
              Print Log
            </button>
            <button
              type="button"
              onClick={() => setActiveTab("label-report")}
              style={
                activeTab === "label-report"
                  ? { borderBottomWidth: 2, borderBottomStyle: "solid", borderBottomColor: "#2563eb" }
                  : undefined
              }
              className={cn(
                "px-4 py-2.5 text-sm font-medium whitespace-nowrap cursor-pointer transition-colors -mb-px border-b-2",
                activeTab === "label-report" ? "text-blue-600" : "border-b-transparent text-gray-600 hover:text-gray-800"
              )}
            >
              Label Report
            </button>
          </div>
        </div>
      </div>

      <div className="flex-1 overflow-auto pt-6">
        {activeTab === "print-log" && (
          <div className="space-y-4">
            <div className="bg-white border border-gray-200 shadow-sm rounded-md overflow-hidden min-h-[200px]">
              {printLoading && (
                <div className="p-6 text-sm text-gray-500">Loading print log…</div>
              )}
              {!printLoading && (
                <Table className="font-sans">
                  <TableHeader>
                    <TableRow className="bg-gray-100 hover:bg-gray-100">
                      <TableHead className={PRINT_LOG_HEAD}>Label ID</TableHead>
                      <TableHead className={PRINT_LOG_HEAD}>Product Name</TableHead>
                      <TableHead className={PRINT_LOG_HEAD}>Product Category</TableHead>
                      <TableHead className={PRINT_LOG_HEAD}>Label Category</TableHead>
                      <TableHead className={PRINT_LOG_HEAD}>Template</TableHead>
                      <TableHead className={PRINT_LOG_HEAD}>Printed at</TableHead>
                      <TableHead className={PRINT_LOG_HEAD}>Printed by</TableHead>
                      <TableHead className={PRINT_LOG_HEAD}>Location</TableHead>
                      <TableHead className={PRINT_LOG_HEAD}>Expiration</TableHead>
                      <TableHead className={`${PRINT_LOG_HEAD} text-center border-r-0`}>Action</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {printRows.length === 0 && (
                      <TableRow>
                        <TableCell colSpan={10} className={`text-center ${PRINT_LOG_CELL} border-r-0 py-10`}>
                          No print records
                        </TableCell>
                      </TableRow>
                    )}
                    {printRows.map((log) => (
                      <TableRow key={log.taskId + log.labelCode}>
                        <TableCell className={PRINT_LOG_CELL}>{toDisplay(log.labelCode)}</TableCell>
                        <TableCell className={PRINT_LOG_CELL}>{toDisplay(log.productName)}</TableCell>
                        <TableCell className={PRINT_LOG_CELL}>{toDisplay(log.productCategoryName)}</TableCell>
                        <TableCell className={PRINT_LOG_CELL}>{toDisplay(log.labelCategoryName)}</TableCell>
                        <TableCell className={PRINT_LOG_CELL}>{templateCell(log.templateText)}</TableCell>
                        <TableCell className={PRINT_LOG_CELL}>{toDisplay(log.printedAt)}</TableCell>
                        <TableCell className={PRINT_LOG_CELL}>{toDisplay(log.printedByName)}</TableCell>
                        <TableCell className={PRINT_LOG_CELL}>{toDisplay(log.locationText)}</TableCell>
                        <TableCell className={PRINT_LOG_CELL}>{formatExpiryDateText(log.expiryDateText, log.printedAt)}</TableCell>
                        <TableCell className="text-center text-sm font-normal font-sans text-gray-900">
                          <div
                            className="inline-flex h-8 items-center justify-center gap-1 rounded-md border border-gray-300 bg-white px-4 text-sm font-normal font-sans text-gray-900 shadow-sm select-none pointer-events-none"
                            aria-label="Reprint"
                          >
                            <Printer className="w-3 h-3 shrink-0 text-gray-700" aria-hidden />
                            <span>Reprint</span>
                          </div>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              )}
            </div>
            <div className="flex flex-col sm:flex-row sm:items-center sm:justify-end gap-2 text-sm text-gray-600">
              <span>
                {printTotal === 0
                  ? "Showing 0 of 0"
                  : `Showing ${(pageIndex - 1) * pageSize + 1}–${Math.min(pageIndex * pageSize, printTotal)} of ${printTotal}`}
              </span>
              <Pagination className="mx-0 w-auto justify-end">
                <PaginationContent>
                  <PaginationItem>
                    <PaginationPrevious
                      className={pageIndex <= 1 ? "pointer-events-none opacity-50" : "cursor-pointer"}
                      onClick={() => pageIndex > 1 && setPageIndex((p) => Math.max(1, p - 1))}
                      aria-disabled={pageIndex <= 1}
                    />
                  </PaginationItem>
                  <PaginationItem>
                    <PaginationLink
                      className="cursor-default"
                      size="default"
                      isActive
                      onClick={(e) => e.preventDefault()}
                    >
                      Page {pageIndex} / {totalPages}
                    </PaginationLink>
                  </PaginationItem>
                  <PaginationItem>
                    <PaginationNext
                      className={pageIndex >= totalPages ? "pointer-events-none opacity-50" : "cursor-pointer"}
                      onClick={() => pageIndex < totalPages && setPageIndex((p) => Math.min(totalPages, p + 1))}
                      aria-disabled={pageIndex >= totalPages}
                    />
                  </PaginationItem>
                </PaginationContent>
              </Pagination>
            </div>
          </div>
        )}

        {activeTab === "label-report" && (
          <div className="space-y-6">
            {labelLoading && <div className="text-sm text-gray-500">Loading label report…</div>}

            {!labelLoading && (
              <>
                <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
                  <Card>
                    <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                      <CardTitle className="text-sm font-medium">Total Labels Printed</CardTitle>
                      <FileText className="h-4 w-4 text-muted-foreground" />
                    </CardHeader>
                    <CardContent>
                      <div className="text-2xl font-bold">{report.summary.totalLabelsPrinted.toLocaleString("en-US")}</div>
                      <p className="text-xs text-muted-foreground">
                        {formatPct(report.summary.totalLabelsPrintedChangeRate)} vs previous period
                      </p>
                    </CardContent>
                  </Card>
                  <Card>
                    <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                      <CardTitle className="text-sm font-medium">Most Printed Category</CardTitle>
                      <BarChart3 className="h-4 w-4 text-muted-foreground" />
                    </CardHeader>
                    <CardContent>
                      <div className="text-2xl font-bold">{toDisplay(report.summary.hottestCategoryName)}</div>
                      <p className="text-xs text-muted-foreground">
                        {report.summary.hottestCategoryCount.toLocaleString("en-US")} label(s) in range
                      </p>
                    </CardContent>
                  </Card>
                  <Card>
                    <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                      <CardTitle className="text-sm font-medium">Top Product</CardTitle>
                      <ArrowUpRight className="h-4 w-4 text-muted-foreground" />
                    </CardHeader>
                    <CardContent>
                      <div className="text-2xl font-bold">{toDisplay(report.summary.topProductName)}</div>
                      <p className="text-xs text-muted-foreground">
                        {report.summary.topProductCount.toLocaleString("en-US")} label(s) in range
                      </p>
                    </CardContent>
                  </Card>
                  <Card>
                    <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                      <CardTitle className="text-sm font-medium">Avg. Daily Prints</CardTitle>
                      <RefreshCw className="h-4 w-4 text-muted-foreground" />
                    </CardHeader>
                    <CardContent>
                      <div className="text-2xl font-bold">
                        {Number.isFinite(report.summary.avgDailyPrints)
                          ? report.summary.avgDailyPrints.toLocaleString("en-US", { maximumFractionDigits: 1 })
                          : "0"}
                      </div>
                      <p className="text-xs text-muted-foreground">
                        {formatPct(report.summary.avgDailyPrintsChangeRate)} vs previous period
                      </p>
                    </CardContent>
                  </Card>
                </div>

                <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                  <Card className="col-span-1">
                    <CardHeader>
                      <CardTitle>Labels by Category</CardTitle>
                      <CardDescription>Distribution of printed labels by label category in the selected range.</CardDescription>
                    </CardHeader>
                    <CardContent className="h-[300px]">
                      {categoryData.length === 0 ? (
                        <div className="h-full flex items-center justify-center text-sm text-gray-500">No data</div>
                      ) : (
                        <ResponsiveContainer width="100%" height="100%">
                          <BarChart data={categoryData}>
                            <CartesianGrid strokeDasharray="3 3" vertical={false} />
                            <XAxis dataKey="name" fontSize={12} tickLine={false} axisLine={false} />
                            <YAxis fontSize={12} tickLine={false} axisLine={false} tickFormatter={(v) => `${v}`} />
                            <Tooltip />
                            <Bar dataKey="count" fill="#facc15" radius={[4, 4, 0, 0]} />
                          </BarChart>
                        </ResponsiveContainer>
                      )}
                    </CardContent>
                  </Card>

                  <Card className="col-span-1">
                    <CardHeader>
                      <CardTitle>Print Volume Trends</CardTitle>
                      <CardDescription>Daily print volume in the current filter window (up to 7 days).</CardDescription>
                    </CardHeader>
                    <CardContent className="h-[300px]">
                      {trendData.length === 0 ? (
                        <div className="h-full flex items-center justify-center text-sm text-gray-500">No data</div>
                      ) : (
                        <ResponsiveContainer width="100%" height="100%">
                          <RechartsLineChart data={trendData}>
                            <CartesianGrid strokeDasharray="3 3" vertical={false} />
                            <XAxis dataKey="date" fontSize={12} tickLine={false} axisLine={false} />
                            <YAxis fontSize={12} tickLine={false} axisLine={false} />
                            <Tooltip />
                            <Line type="monotone" dataKey="count" stroke="#dc2626" strokeWidth={2} dot={{ r: 4 }} activeDot={{ r: 6 }} />
                          </RechartsLineChart>
                        </ResponsiveContainer>
                      )}
                    </CardContent>
                  </Card>
                </div>

                <Card>
                  <CardHeader>
                    <CardTitle>Most Used Products</CardTitle>
                  </CardHeader>
                  <CardContent>
                    <Table>
                      <TableHeader>
                        <TableRow>
                          <TableHead>Product Name</TableHead>
                          <TableHead>Category</TableHead>
                          <TableHead className="text-right">Total Printed</TableHead>
                          <TableHead className="text-right">Usage %</TableHead>
                        </TableRow>
                      </TableHeader>
                      <TableBody>
                        {report.mostUsedProducts.length === 0 && (
                          <TableRow>
                            <TableCell colSpan={4} className="text-center text-sm text-gray-500">
                              No data
                            </TableCell>
                          </TableRow>
                        )}
                        {report.mostUsedProducts.map((row, i) => (
                          <TableRow key={`${row.productName}-${i}`}>
                            <TableCell className="font-medium">{toDisplay(row.productName)}</TableCell>
                            <TableCell>{toDisplay(row.categoryName)}</TableCell>
                            <TableCell className="text-right font-numeric">{row.totalPrinted.toLocaleString("en-US")}</TableCell>
                            <TableCell className="text-right font-numeric">
                              {Number.isFinite(row.usagePercent) ? `${row.usagePercent.toFixed(1)}%` : "—"}
                            </TableCell>
                          </TableRow>
                        ))}
                      </TableBody>
                    </Table>
                  </CardContent>
                </Card>
              </>
            )}
          </div>
        )}
      </div>
    </div>
  );
}
