import { useEffect, useMemo, useState } from "react";
import { acotService } from "@/services/dashboard/acotService";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Separator } from "@/components/ui/separator";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import {
  Area,
  CartesianGrid,
  ComposedChart,
  Legend,
  Line,
  ResponsiveContainer,
  Tooltip,
  XAxis,
  YAxis,
} from "recharts";
import type { TooltipProps } from "recharts";
import { Package, Truck, Gauge, TrendingUp } from "lucide-react";
import PeriodSelectionPopover, {
  type QuickPreset,
} from "@/components/dashboard/PeriodSelectionPopover";
import type { CustomPeriod, NaturalLanguagePeriodResult } from "@/utils/naturalLanguagePeriod";
import { CARD_STYLES } from "@/lib/dashboard/designTokens";
import {
  DashboardSectionHeader,
  DashboardStatCard,
  DashboardStatCardSkeleton,
  ChartSkeleton,
  DashboardEmptyState,
  DashboardErrorState,
  TOOLTIP_STYLES,
  METRIC_COLORS,
} from "@/components/dashboard/shared";
import { Tooltip as TooltipUI, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { toDateOnly } from "@/utils/businessTime";

type ComparisonValue = {
  absolute: number | null;
  percentage: number | null;
};

type OperationsTotals = {
  ordersPicked: number;
  piecesPicked: number;
  ticketCount: number;
  pickingHours: number;
  ordersShipped: number;
  piecesShipped: number;
  ordersPerHour: number;
  piecesPerHour: number;
  avgPickingSpeed: number;
};

type OperationsComparison = {
  ordersPicked?: ComparisonValue;
  piecesPicked?: ComparisonValue;
  ordersShipped?: ComparisonValue;
  piecesShipped?: ComparisonValue;
  ordersPerHour?: ComparisonValue;
  piecesPerHour?: ComparisonValue;
};

type EmployeePickingEntry = {
  employeeId: number;
  name: string;
  ticketCount: number;
  ordersPicked: number;
  piecesPicked: number;
  pickingHours: number;
  avgPickingSpeed: number | null;
};

type EmployeeShippingEntry = {
  employeeId: number;
  name: string;
  ordersShipped: number;
  piecesShipped: number;
};

type TrendPoint = {
  date: string;
  timestamp: string;
  ordersPicked: number;
  piecesPicked: number;
  ordersShipped: number;
  piecesShipped: number;
};

type OperationsMetricsResponse = {
  dateRange?: { label?: string };
  totals: OperationsTotals;
  previousTotals?: OperationsTotals | null;
  comparison?: OperationsComparison | null;
  byEmployee: {
    picking: EmployeePickingEntry[];
    shipping: EmployeeShippingEntry[];
  };
  trend: TrendPoint[];
};

type ChartSeriesKey = "ordersPicked" | "piecesPicked" | "ordersShipped" | "piecesShipped";

type GroupByOption = "day" | "week" | "month";

type ChartPoint = {
  label: string;
  timestamp: string | null;
  ordersPicked: number | null;
  piecesPicked: number | null;
  ordersShipped: number | null;
  piecesShipped: number | null;
  tooltipLabel: string;
};

const chartColors: Record<ChartSeriesKey, string> = {
  ordersPicked: METRIC_COLORS.orders,
  piecesPicked: METRIC_COLORS.aov,
  ordersShipped: METRIC_COLORS.profit,
  piecesShipped: METRIC_COLORS.secondary,
};

const SERIES_LABELS: Record<ChartSeriesKey, string> = {
  ordersPicked: "Orders Picked",
  piecesPicked: "Pieces Picked",
  ordersShipped: "Orders Shipped",
  piecesShipped: "Pieces Shipped",
};

const SERIES_DEFINITIONS: Array<{
  key: ChartSeriesKey;
  label: string;
}> = [
  { key: "ordersPicked", label: SERIES_LABELS.ordersPicked },
  { key: "piecesPicked", label: SERIES_LABELS.piecesPicked },
  { key: "ordersShipped", label: SERIES_LABELS.ordersShipped },
  { key: "piecesShipped", label: SERIES_LABELS.piecesShipped },
];

const GROUP_BY_CHOICES: Array<{ value: GroupByOption; label: string }> = [
  { value: "day", label: "Days" },
  { value: "week", label: "Weeks" },
  { value: "month", label: "Months" },
];

const MONTHS = [
  "January", "February", "March", "April", "May", "June",
  "July", "August", "September", "October", "November", "December",
];

const MONTH_COUNT_LIMIT = 999;
const QUARTER_COUNT_LIMIT = 999;
const YEAR_COUNT_LIMIT = 999;

const formatMonthLabel = (year: number, monthIndex: number) => `${MONTHS[monthIndex]} ${year}`;

const formatQuarterLabel = (year: number, quarterIndex: number) => `Q${quarterIndex + 1} ${year}`;

function formatPeriodRangeLabel(period: CustomPeriod): string {
  const range = computePeriodRange(period);
  if (!range) return "";

  const start = range.start;
  const end = range.end;

  if (period.type === "month") {
    const startLabel = formatMonthLabel(start.getFullYear(), start.getMonth());
    const endLabel = formatMonthLabel(end.getFullYear(), end.getMonth());
    return period.count === 1 ? startLabel : `${startLabel} – ${endLabel}`;
  }

  if (period.type === "quarter") {
    const startQuarter = Math.floor(start.getMonth() / 3);
    const endQuarter = Math.floor(end.getMonth() / 3);
    const startLabel = formatQuarterLabel(start.getFullYear(), startQuarter);
    const endLabel = formatQuarterLabel(end.getFullYear(), endQuarter);
    return period.count === 1 ? startLabel : `${startLabel} – ${endLabel}`;
  }

  const startYear = start.getFullYear();
  const endYear = end.getFullYear();
  return period.count === 1 ? `${startYear}` : `${startYear} – ${endYear}`;
}

const formatNumber = (value: number, decimals = 0) => {
  if (!Number.isFinite(value)) return "0";
  return value.toLocaleString("en-US", {
    minimumFractionDigits: decimals,
    maximumFractionDigits: decimals,
  });
};

const formatHours = (value: number) => {
  if (!Number.isFinite(value)) return "0h";
  return `${value.toFixed(1)}h`;
};

const ensureValidCustomPeriod = (period: CustomPeriod): CustomPeriod => {
  if (period.count < 1) {
    return { ...period, count: 1 };
  }

  switch (period.type) {
    case "month":
      return {
        ...period,
        startMonth: Math.min(Math.max(period.startMonth, 0), 11),
        count: Math.min(period.count, MONTH_COUNT_LIMIT),
      };
    case "quarter":
      return {
        ...period,
        startQuarter: Math.min(Math.max(period.startQuarter, 0), 3),
        count: Math.min(period.count, QUARTER_COUNT_LIMIT),
      };
    case "year":
    default:
      return {
        ...period,
        count: Math.min(period.count, YEAR_COUNT_LIMIT),
      };
  }
};

function computePeriodRange(period: CustomPeriod): { start: Date; end: Date } | null {
  const safePeriod = ensureValidCustomPeriod(period);
  let start: Date;

  if (safePeriod.type === "month") {
    start = new Date(safePeriod.startYear, safePeriod.startMonth, 1, 0, 0, 0, 0);
    const endExclusive = new Date(start);
    endExclusive.setMonth(endExclusive.getMonth() + safePeriod.count);
    endExclusive.setMilliseconds(endExclusive.getMilliseconds() - 1);
    return { start, end: endExclusive };
  }

  if (safePeriod.type === "quarter") {
    const startMonth = safePeriod.startQuarter * 3;
    start = new Date(safePeriod.startYear, startMonth, 1, 0, 0, 0, 0);
    const endExclusive = new Date(start);
    endExclusive.setMonth(endExclusive.getMonth() + safePeriod.count * 3);
    endExclusive.setMilliseconds(endExclusive.getMilliseconds() - 1);
    return { start, end: endExclusive };
  }

  start = new Date(safePeriod.startYear, 0, 1, 0, 0, 0, 0);
  const endExclusive = new Date(start);
  endExclusive.setFullYear(endExclusive.getFullYear() + safePeriod.count);
  endExclusive.setMilliseconds(endExclusive.getMilliseconds() - 1);
  return { start, end: endExclusive };
}

const OperationsMetrics = () => {
  const currentDate = useMemo(() => new Date(), []);
  const currentYear = currentDate.getFullYear();

  const [customPeriod, setCustomPeriod] = useState<CustomPeriod>({
    type: "month",
    startYear: currentYear,
    startMonth: currentDate.getMonth(),
    count: 1,
  });
  const [isLast30DaysMode, setIsLast30DaysMode] = useState<boolean>(true);
  const [isPeriodPopoverOpen, setIsPeriodPopoverOpen] = useState<boolean>(false);
  const [metrics, setMetrics] = useState<Record<ChartSeriesKey, boolean>>({
    ordersPicked: true,
    piecesPicked: false,
    ordersShipped: true,
    piecesShipped: false,
  });
  const [groupBy, setGroupBy] = useState<GroupByOption>("day");
  const [data, setData] = useState<OperationsMetricsResponse | null>(null);
  const [loading, setLoading] = useState<boolean>(true);
  const [error, setError] = useState<string | null>(null);

  const selectedRange = useMemo(() => {
    if (isLast30DaysMode) {
      const end = new Date(currentDate);
      const start = new Date(currentDate);
      start.setHours(0, 0, 0, 0);
      end.setHours(23, 59, 59, 999);
      start.setDate(start.getDate() - 29);
      return { start, end };
    }
    return computePeriodRange(customPeriod);
  }, [isLast30DaysMode, customPeriod, currentDate]);

  const effectiveRangeEnd = useMemo(() => {
    if (!selectedRange) return null;
    const rangeEndMs = selectedRange.end.getTime();
    const currentMs = currentDate.getTime();
    const startMs = selectedRange.start.getTime();
    const clampedMs = Math.min(rangeEndMs, currentMs);
    const safeEndMs = clampedMs < startMs ? startMs : clampedMs;
    return new Date(safeEndMs);
  }, [selectedRange, currentDate]);

  const requestRange = useMemo(() => {
    if (!selectedRange) return null;
    const end = effectiveRangeEnd ?? selectedRange.end;
    return {
      start: new Date(selectedRange.start),
      end: new Date(end),
    };
  }, [selectedRange, effectiveRangeEnd]);

  useEffect(() => {
    let cancelled = false;

    const fetchData = async () => {
      setLoading(true);
      setError(null);

      try {
        const params: Record<string, string> = {};

        if (isLast30DaysMode) {
          params.timeRange = "last30days";
        } else {
          if (!selectedRange || !requestRange) {
            setData(null);
            return;
          }
          params.timeRange = "custom";
          // Date-only strings = business dates; the server resolves them to
          // business-day bounds (1am ET / Chicago midnight). Never send
          // browser-local-midnight instants.
          params.startDate = toDateOnly(requestRange.start);
          params.endDate = toDateOnly(requestRange.end);
        }

        // @ts-expect-error - acotService is a JS file, TypeScript can't infer the param type
        const response = (await acotService.getOperationsMetrics(params)) as OperationsMetricsResponse;
        if (!cancelled) {
          setData(response);
        }
      } catch (err: unknown) {
        if (!cancelled) {
          let message = "Failed to load operations metrics";
          if (typeof err === "object" && err !== null) {
            const maybeError = err as { response?: { data?: { error?: unknown } }; message?: unknown };
            const responseError = maybeError.response?.data?.error;
            if (typeof responseError === "string" && responseError.trim().length > 0) {
              message = responseError;
            } else if (typeof maybeError.message === "string") {
              message = maybeError.message;
            }
          }
          setError(message);
        }
      } finally {
        if (!cancelled) {
          setLoading(false);
        }
      }
    };

    void fetchData();
    return () => { cancelled = true; };
  }, [isLast30DaysMode, selectedRange, requestRange]);

  const cards = useMemo(() => {
    if (!data?.totals) return [];

    const totals = data.totals;
    const comparison = data.comparison ?? {};

    return [
      {
        key: "ordersPicked",
        title: "Orders Picked",
        value: formatNumber(totals.ordersPicked),
        description: `${formatNumber(totals.piecesPicked)} pieces`,
        trendValue: comparison.ordersPicked?.percentage,
        iconColor: "blue" as const,
        tooltip: "Total distinct orders picked (ship-together groups count as 1).",
      },
      {
        key: "ordersShipped",
        title: "Orders Shipped",
        value: formatNumber(totals.ordersShipped),
        description: `${formatNumber(totals.piecesShipped)} pieces`,
        trendValue: comparison.ordersShipped?.percentage,
        iconColor: "emerald" as const,
        tooltip: "Total orders shipped (ship-together groups count as 1).",
      },
      {
        key: "productivity",
        title: "Productivity",
        value: `${formatNumber(totals.ordersPerHour, 1)}/h`,
        description: `${formatNumber(totals.piecesPerHour, 1)} pieces/hour`,
        trendValue: comparison.ordersPerHour?.percentage,
        iconColor: "purple" as const,
        tooltip: "Orders and pieces picked per picking hour.",
      },
      {
        key: "pickingSpeed",
        title: "Picking Speed",
        value: `${formatNumber(totals.avgPickingSpeed, 1)}/h`,
        description: `${formatHours(totals.pickingHours)} picking time`,
        iconColor: "orange" as const,
        tooltip: "Average pieces picked per hour while actively picking.",
      },
    ];
  }, [data]);

  const chartData = useMemo<ChartPoint[]>(() => {
    if (!data?.trend?.length) return [];

    const groupedData = new Map<string, {
      label: string;
      tooltipLabel: string;
      timestamp: string;
      ordersPicked: number;
      piecesPicked: number;
      ordersShipped: number;
      piecesShipped: number;
    }>();

    data.trend.forEach((point) => {
      const date = new Date(point.timestamp);
      let key: string;
      let label: string;
      let tooltipLabel: string;

      switch (groupBy) {
        case "week": {
          const weekStart = new Date(date);
          weekStart.setDate(date.getDate() - date.getDay());
          key = weekStart.toISOString().split("T")[0];
          label = weekStart.toLocaleDateString("en-US", { month: "short", day: "numeric" });
          tooltipLabel = `Week of ${weekStart.toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" })}`;
          break;
        }
        case "month": {
          key = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}`;
          label = date.toLocaleDateString("en-US", { month: "short", year: "numeric" });
          tooltipLabel = date.toLocaleDateString("en-US", { month: "long", year: "numeric" });
          break;
        }
        default: {
          key = point.date;
          label = date.toLocaleDateString("en-US", { month: "short", day: "numeric" });
          tooltipLabel = date.toLocaleDateString("en-US", { weekday: "short", month: "short", day: "numeric", year: "numeric" });
        }
      }

      const existing = groupedData.get(key);
      if (existing) {
        existing.ordersPicked += point.ordersPicked || 0;
        existing.piecesPicked += point.piecesPicked || 0;
        existing.ordersShipped += point.ordersShipped || 0;
        existing.piecesShipped += point.piecesShipped || 0;
      } else {
        groupedData.set(key, {
          label,
          tooltipLabel,
          timestamp: point.timestamp,
          ordersPicked: point.ordersPicked || 0,
          piecesPicked: point.piecesPicked || 0,
          ordersShipped: point.ordersShipped || 0,
          piecesShipped: point.piecesShipped || 0,
        });
      }
    });

    return Array.from(groupedData.entries())
      .sort(([a], [b]) => a.localeCompare(b))
      .map(([, group]) => ({
        label: group.label,
        timestamp: group.timestamp,
        ordersPicked: group.ordersPicked,
        piecesPicked: group.piecesPicked,
        ordersShipped: group.ordersShipped,
        piecesShipped: group.piecesShipped,
        tooltipLabel: group.tooltipLabel,
      }));
  }, [data, groupBy]);

  const selectedRangeLabel = useMemo(() => {
    if (isLast30DaysMode) return "Last 30 Days";
    const label = formatPeriodRangeLabel(customPeriod);
    if (!label) return "";

    if (!selectedRange || !effectiveRangeEnd) return label;

    const isPartial = effectiveRangeEnd.getTime() < selectedRange.end.getTime();
    if (!isPartial) return label;

    const partialLabel = effectiveRangeEnd.toLocaleDateString("en-US", {
      month: "short",
      day: "numeric",
    });

    return `${label} (through ${partialLabel})`;
  }, [isLast30DaysMode, customPeriod, selectedRange, effectiveRangeEnd]);

  const hasActiveMetrics = useMemo(() => Object.values(metrics).some(Boolean), [metrics]);
  const hasOrdersMetric = metrics.ordersPicked || metrics.ordersShipped;
  const hasPiecesMetric = metrics.piecesPicked || metrics.piecesShipped;
  const useDualAxis = hasOrdersMetric && hasPiecesMetric;
  const hasData = chartData.length > 0;

  const handleGroupByChange = (value: string) => {
    setGroupBy(value as GroupByOption);
  };

  const toggleMetric = (series: ChartSeriesKey) => {
    setMetrics((prev) => ({
      ...prev,
      [series]: !prev[series],
    }));
  };

  const handleNaturalLanguageResult = (result: NaturalLanguagePeriodResult) => {
    if (result === "last30days") {
      setIsLast30DaysMode(true);
      return;
    }
    if (result) {
      setIsLast30DaysMode(false);
      setCustomPeriod(result);
    }
  };

  const handleQuickPeriod = (preset: QuickPreset) => {
    const now = new Date();
    const year = now.getFullYear();
    const month = now.getMonth();
    const quarter = Math.floor(month / 3);

    switch (preset) {
      case "last30days":
        setIsLast30DaysMode(true);
        break;
      case "thisMonth":
        setIsLast30DaysMode(false);
        setCustomPeriod({ type: "month", startYear: year, startMonth: month, count: 1 });
        break;
      case "lastMonth":
        setIsLast30DaysMode(false);
        const lastMonth = month === 0 ? 11 : month - 1;
        const lastMonthYear = month === 0 ? year - 1 : year;
        setCustomPeriod({ type: "month", startYear: lastMonthYear, startMonth: lastMonth, count: 1 });
        break;
      case "thisQuarter":
        setIsLast30DaysMode(false);
        setCustomPeriod({ type: "quarter", startYear: year, startQuarter: quarter, count: 1 });
        break;
      case "lastQuarter":
        setIsLast30DaysMode(false);
        const lastQuarter = quarter === 0 ? 3 : quarter - 1;
        const lastQuarterYear = quarter === 0 ? year - 1 : year;
        setCustomPeriod({ type: "quarter", startYear: lastQuarterYear, startQuarter: lastQuarter, count: 1 });
        break;
      case "thisYear":
        setIsLast30DaysMode(false);
        setCustomPeriod({ type: "year", startYear: year, count: 1 });
        break;
      default:
        break;
    }
  };

  const headerActions = !error ? (
    <>
      <PeriodSelectionPopover
        open={isPeriodPopoverOpen}
        onOpenChange={setIsPeriodPopoverOpen}
        selectedLabel={selectedRangeLabel}
        referenceDate={currentDate}
        isLast30DaysActive={isLast30DaysMode}
        onQuickSelect={handleQuickPeriod}
        onApplyResult={handleNaturalLanguageResult}
      />
    </>
  ) : null;

  return (
    <Card className={`w-full h-full ${CARD_STYLES.elevated}`}>
      <DashboardSectionHeader
        title="Operations"
        size="large"
        actions={headerActions}
      />

      <CardContent className="p-6 pt-0">
        {!error && (
          loading ? (
            <SkeletonStats />
          ) : (
            cards.length > 0 && <OperationsStatGrid cards={cards} />
          )
        )}

        {!error && (
          <div className="flex items-center flex-col sm:flex-row gap-0 sm:gap-4">
            <div className="flex flex-wrap gap-1">
              {SERIES_DEFINITIONS.map((series) => (
                <Button
                  key={series.key}
                  variant={metrics[series.key] ? "default" : "outline"}
                  size="sm"
                  onClick={() => toggleMetric(series.key)}
                >
                  {series.label}
                </Button>
              ))}
            </div>

            <Separator orientation="vertical" className="h-6 hidden sm:block" />
            <Separator orientation="horizontal" className="sm:hidden w-20 my-2" />

            <div className="flex items-center gap-2">
              <div className="text-sm text-muted-foreground">Group:</div>
              <Select value={groupBy} onValueChange={handleGroupByChange}>
                <SelectTrigger className="w-[100px]">
                  <SelectValue placeholder="Group By" />
                </SelectTrigger>
                <SelectContent>
                  {GROUP_BY_CHOICES.map((option) => (
                    <SelectItem key={option.value} value={option.value}>
                      {option.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          </div>
        )}

        {loading ? (
          <div className="flex flex-col lg:flex-row gap-6 mt-4">
            <div className="w-full lg:w-[45%]">
              <LeaderboardTableSkeleton />
            </div>
            <div className="w-full lg:w-[55%]">
              <ChartSkeleton type="area" height="md" withCard={false} />
            </div>
          </div>
        ) : error ? (
          <DashboardErrorState error={`Failed to load operations data: ${error}`} className="mx-0 my-0" />
        ) : !hasData ? (
          <DashboardEmptyState
            icon={Package}
            title="No operations data available"
            description="Try selecting a different time range"
          />
        ) : (
          <div className="flex flex-col lg:flex-row gap-6 mt-4">
            <div className="w-full lg:w-[45%]">
              <OperationsLeaderboard
                picking={data?.byEmployee?.picking ?? []}
                shipping={data?.byEmployee?.shipping ?? []}
              />
            </div>
            <div className={`h-[300px] w-full lg:w-[55%] ${CARD_STYLES.base} rounded-lg p-0 relative`}>
              {!hasActiveMetrics ? (
                <DashboardEmptyState
                  icon={TrendingUp}
                  title="No metrics selected"
                  description="Select at least one metric to visualize."
                />
              ) : (
                <ResponsiveContainer width="100%" height="100%">
                  <ComposedChart data={chartData} margin={{ top: 5, right: 15, left: 15, bottom: 5 }}>
                    <defs>
                      <linearGradient id="operationsOrdersPicked" x1="0" y1="0" x2="0" y2="1">
                        <stop offset="5%" stopColor={chartColors.ordersPicked} stopOpacity={0.8} />
                        <stop offset="95%" stopColor={chartColors.ordersPicked} stopOpacity={0.3} />
                      </linearGradient>
                    </defs>
                    <CartesianGrid strokeDasharray="3 3" className="stroke-muted" />
                    <XAxis
                      dataKey="label"
                      className="text-xs text-muted-foreground"
                      tick={{ fill: "currentColor" }}
                    />
                    <YAxis
                      yAxisId="left"
                      tickFormatter={(value: number) => formatNumber(value)}
                      className="text-xs text-muted-foreground"
                      tick={{ fill: "currentColor" }}
                    />
                    {useDualAxis && (
                      <YAxis
                        yAxisId="right"
                        orientation="right"
                        tickFormatter={(value: number) => formatNumber(value)}
                        className="text-xs text-muted-foreground"
                        tick={{ fill: "currentColor" }}
                      />
                    )}
                    <Tooltip content={<OperationsTooltip />} />
                    <Legend formatter={(value: string) => SERIES_LABELS[value as ChartSeriesKey] ?? value} />

                    {metrics.ordersPicked && (
                      <Area
                        yAxisId="left"
                        type="monotone"
                        dataKey="ordersPicked"
                        name={SERIES_LABELS.ordersPicked}
                        stroke={chartColors.ordersPicked}
                        fill="url(#operationsOrdersPicked)"
                        strokeWidth={2}
                      />
                    )}
                    {metrics.ordersShipped && (
                      <Line
                        yAxisId="left"
                        type="monotone"
                        dataKey="ordersShipped"
                        name={SERIES_LABELS.ordersShipped}
                        stroke={chartColors.ordersShipped}
                        strokeWidth={2}
                        dot={false}
                        activeDot={{ r: 4 }}
                        connectNulls
                      />
                    )}
                    {metrics.piecesPicked && (
                      <Line
                        yAxisId={useDualAxis ? "right" : "left"}
                        type="monotone"
                        dataKey="piecesPicked"
                        name={SERIES_LABELS.piecesPicked}
                        stroke={chartColors.piecesPicked}
                        strokeWidth={2}
                        strokeDasharray="5 3"
                        dot={false}
                        activeDot={{ r: 4 }}
                        connectNulls
                      />
                    )}
                    {metrics.piecesShipped && (
                      <Line
                        yAxisId={useDualAxis ? "right" : "left"}
                        type="monotone"
                        dataKey="piecesShipped"
                        name={SERIES_LABELS.piecesShipped}
                        stroke={chartColors.piecesShipped}
                        strokeWidth={2}
                        strokeDasharray="3 3"
                        dot={false}
                        activeDot={{ r: 4 }}
                        connectNulls
                      />
                    )}
                  </ComposedChart>
                </ResponsiveContainer>
              )}
            </div>
          </div>
        )}
      </CardContent>
    </Card>
  );
};

type OperationsStatCardConfig = {
  key: string;
  title: string;
  value: string;
  description?: string;
  trendValue?: number | null;
  trendInverted?: boolean;
  iconColor: "blue" | "orange" | "emerald" | "purple" | "cyan" | "amber";
  tooltip?: string;
};

const ICON_MAP = {
  ordersPicked: Package,
  ordersShipped: Truck,
  productivity: Gauge,
  pickingSpeed: TrendingUp,
} as const;

function OperationsStatGrid({ cards }: { cards: OperationsStatCardConfig[] }) {
  return (
    <div className="grid grid-cols-2 lg:grid-cols-4 gap-4 py-4 w-full dashboard-stagger">
      {cards.map((card) => (
        <DashboardStatCard
          key={card.key}
          title={card.title}
          value={card.value}
          subtitle={card.description}
          trend={
            card.trendValue != null && Number.isFinite(card.trendValue)
              ? {
                  value: card.trendValue,
                  moreIsBetter: !card.trendInverted,
                }
              : undefined
          }
          icon={ICON_MAP[card.key as keyof typeof ICON_MAP]}
          iconColor={card.iconColor}
          tooltip={card.tooltip}
        />
      ))}
    </div>
  );
}

function SkeletonStats() {
  return (
    <div className="grid grid-cols-2 lg:grid-cols-4 gap-4 py-4 w-full">
      {Array.from({ length: 4 }).map((_, index) => (
        <DashboardStatCardSkeleton key={index} hasIcon hasSubtitle />
      ))}
    </div>
  );
}

const OperationsTooltip = ({ active, payload, label }: TooltipProps<number, string>) => {
  if (!active || !payload?.length) return null;

  const basePoint = payload[0]?.payload as ChartPoint | undefined;
  const resolvedLabel = basePoint?.tooltipLabel ?? label;

  const desiredOrder: ChartSeriesKey[] = ["ordersPicked", "piecesPicked", "ordersShipped", "piecesShipped"];
  const payloadMap = new Map(payload.map((entry) => [entry.dataKey as ChartSeriesKey, entry]));
  const orderedPayload = desiredOrder
    .map((key) => payloadMap.get(key))
    .filter((entry): entry is (typeof payload)[0] => entry !== undefined);

  return (
    <div className={TOOLTIP_STYLES.container}>
      <p className={TOOLTIP_STYLES.header}>{resolvedLabel}</p>
      <div className={TOOLTIP_STYLES.content}>
        {orderedPayload.map((entry, index) => {
          const key = (entry.dataKey ?? "") as ChartSeriesKey;
          const rawValue = entry.value;
          const formattedValue = rawValue != null ? formatNumber(rawValue as number) : "—";

          return (
            <div key={`${key}-${index}`} className={TOOLTIP_STYLES.row}>
              <div className={TOOLTIP_STYLES.rowLabel}>
                <span
                  className={TOOLTIP_STYLES.dot}
                  style={{ backgroundColor: entry.stroke || entry.color || "#888" }}
                />
                <span className={TOOLTIP_STYLES.name}>
                  {SERIES_LABELS[key] ?? entry.name ?? key}
                </span>
              </div>
              <span className={TOOLTIP_STYLES.value}>{formattedValue}</span>
            </div>
          );
        })}
      </div>
    </div>
  );
};

function LeaderboardTableSkeleton() {
  return (
    <div className={`h-[280px] rounded-lg border ${CARD_STYLES.base} overflow-hidden`}>
      <div className="p-3 border-b bg-muted/30">
        <div className="h-4 w-32 bg-muted rounded animate-pulse" />
      </div>
      <div className="p-2 space-y-2">
        {Array.from({ length: 8 }).map((_, i) => (
          <div key={i} className="flex items-center gap-3 px-2 py-1.5">
            <div className="h-5 w-5 bg-muted rounded-full animate-pulse" />
            <div className="h-3 w-20 bg-muted rounded animate-pulse" />
            <div className="flex-1" />
            <div className="h-3 w-10 bg-muted rounded animate-pulse" />
            <div className="h-3 w-10 bg-muted rounded animate-pulse" />
          </div>
        ))}
      </div>
    </div>
  );
}

type LeaderboardEntry = {
  employeeId: number;
  name: string;
  ordersPicked: number;
  piecesPicked: number;
  ordersShipped: number;
  piecesShipped: number;
  pickingHours: number;
  pickingSpeed: number | null;
  productivity: number;
};

function OperationsLeaderboard({
  picking,
  shipping,
  maxRows = 20,
}: {
  picking: EmployeePickingEntry[];
  shipping: EmployeeShippingEntry[];
  maxRows?: number;
}) {
  const leaderboard = useMemo<LeaderboardEntry[]>(() => {
    const employeeMap = new Map<number, LeaderboardEntry>();

    picking.forEach((emp) => {
      employeeMap.set(emp.employeeId, {
        employeeId: emp.employeeId,
        name: emp.name,
        ordersPicked: emp.ordersPicked,
        piecesPicked: emp.piecesPicked,
        ordersShipped: 0,
        piecesShipped: 0,
        pickingHours: emp.pickingHours || 0,
        pickingSpeed: emp.avgPickingSpeed,
        productivity: emp.pickingHours > 0 ? emp.ordersPicked / emp.pickingHours : 0,
      });
    });

    shipping.forEach((emp) => {
      const existing = employeeMap.get(emp.employeeId);
      if (existing) {
        existing.ordersShipped = emp.ordersShipped;
        existing.piecesShipped = emp.piecesShipped;
      } else {
        employeeMap.set(emp.employeeId, {
          employeeId: emp.employeeId,
          name: emp.name,
          ordersPicked: 0,
          piecesPicked: 0,
          ordersShipped: emp.ordersShipped,
          piecesShipped: emp.piecesShipped,
          pickingHours: 0,
          pickingSpeed: null,
          productivity: 0,
        });
      }
    });

    return Array.from(employeeMap.values())
      .sort((a, b) => b.piecesPicked - a.piecesPicked)
      .slice(0, maxRows);
  }, [picking, shipping, maxRows]);

  const totalEmployees = Math.max(picking.length, shipping.length);

  if (leaderboard.length === 0) {
    return (
      <div className={`h-[300px] rounded-lg border ${CARD_STYLES.base} flex items-center justify-center`}>
        <p className="text-sm text-muted-foreground">No employee data</p>
      </div>
    );
  }

  return (
    <div className={`h-[300px] rounded-lg border ${CARD_STYLES.base} overflow-hidden flex flex-col`}>
      <div className="p-3 border-b bg-muted/30 flex-none">
        <h4 className="text-sm font-medium">Top Performers</h4>
      </div>
      <div className="flex-1 overflow-auto">
        <Table>
          <TableHeader>
            <TableRow className="hover:bg-transparent">
              <TableHead className="h-8 text-xs px-2 w-8" />
              <TableHead className="h-8 text-xs px-2">Name</TableHead>
              <TableHead className="h-8 text-xs px-2 text-right">Picked</TableHead>
              <TableHead className="h-8 text-xs px-2 text-right">Shipped</TableHead>
              <TableHead className="h-8 text-xs px-2 text-right">
                <TooltipUI>
                  <TooltipTrigger asChild>
                    <span className="cursor-help">Hours</span>
                  </TooltipTrigger>
                  <TooltipContent>
                    <p>Time spent picking only</p>
                  </TooltipContent>
                </TooltipUI>
              </TableHead>
              <TableHead className="h-8 text-xs px-2 text-right">Speed</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {leaderboard.map((emp, index) => (
              <TableRow key={emp.employeeId}>
                <TableCell className="py-1.5 px-2 w-8 text-xs text-muted-foreground text-center">
                  {index + 1}
                </TableCell>
                <TableCell className="py-1.5 px-2 text-xs font-medium truncate max-w-[100px]">
                  {emp.name}
                </TableCell>
                <TableCell className="py-1.5 px-2 text-xs text-right">
                  <span className="font-medium">{formatNumber(emp.piecesPicked)}</span>
                  <span className="text-muted-foreground ml-1 text-[10px]">
                    ({formatNumber(emp.ordersPicked)})
                  </span>
                </TableCell>
                <TableCell className="py-1.5 px-2 text-xs text-right text-muted-foreground">
                  {emp.ordersShipped > 0 ? formatNumber(emp.ordersShipped) : "—"}
                </TableCell>
                <TableCell className="py-1.5 px-2 text-xs text-right text-muted-foreground">
                  {emp.pickingHours > 0 ? formatHours(emp.pickingHours) : "—"}
                </TableCell>
                <TableCell className="py-1.5 px-2 text-xs text-right">
                  {emp.pickingSpeed != null ? (
                    <span className="text-emerald-600 dark:text-emerald-400 font-medium">
                      {formatNumber(emp.pickingSpeed, 0)}/h
                    </span>
                  ) : (
                    <span className="text-muted-foreground">—</span>
                  )}
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </div>
      {totalEmployees > maxRows && (
        <div className="p-2 border-t text-center flex-none">
          <span className="text-xs text-muted-foreground">
            +{totalEmployees - maxRows} more employees
          </span>
        </div>
      )}
    </div>
  );
}

export default OperationsMetrics;
