import { useEffect, useMemo, useState, useCallback } 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 {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import {
  Bar,
  CartesianGrid,
  Legend,
  Line,
  ComposedChart,
  ResponsiveContainer,
  Tooltip,
  XAxis,
  YAxis,
} from "recharts";
import type { TooltipProps } from "recharts";
import { Clock, Users, AlertTriangle, ChevronLeft, ChevronRight, Calendar, TrendingUp } from "lucide-react";
import { CARD_STYLES } from "@/lib/dashboard/designTokens";
import {
  DashboardSectionHeader,
  DashboardStatCard,
  DashboardStatCardSkeleton,
  ChartSkeleton,
  DashboardEmptyState,
  DashboardErrorState,
  TOOLTIP_STYLES,
  METRIC_COLORS,
} from "@/components/dashboard/shared";

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

type PayPeriodWeek = {
  start: string;
  end: string;
  label: string;
};

type PayPeriod = {
  start: string;
  end: string;
  label: string;
  week1: PayPeriodWeek;
  week2: PayPeriodWeek;
  isCurrent: boolean;
};

type PayrollTotals = {
  hours: number;
  breakHours: number;
  overtimeHours: number;
  regularHours: number;
  activeEmployees: number;
  fte: number;
  avgHoursPerEmployee: number;
};

type PayrollComparison = {
  hours?: ComparisonValue;
  overtimeHours?: ComparisonValue;
  fte?: ComparisonValue;
  activeEmployees?: ComparisonValue;
};

type EmployeePayrollEntry = {
  employeeId: number;
  name: string;
  week1Hours: number;
  week1BreakHours: number;
  week1Overtime: number;
  week1Regular: number;
  week2Hours: number;
  week2BreakHours: number;
  week2Overtime: number;
  week2Regular: number;
  totalHours: number;
  totalBreakHours: number;
  overtimeHours: number;
  regularHours: number;
};

type WeekSummary = {
  week: number;
  start: string;
  end: string;
  hours: number;
  overtime: number;
  regular: number;
};

type PayrollMetricsResponse = {
  payPeriod: PayPeriod;
  totals: PayrollTotals;
  previousTotals?: PayrollTotals | null;
  comparison?: PayrollComparison | null;
  byEmployee: EmployeePayrollEntry[];
  byWeek: WeekSummary[];
};

type PeriodCountOption = 1 | 3 | 6 | 12;

const PERIOD_COUNT_OPTIONS: { value: PeriodCountOption; label: string }[] = [
  { value: 1, label: "1 period" },
  { value: 3, label: "3 periods" },
  { value: 6, label: "6 periods" },
  { value: 12, label: "12 periods" },
];

const chartColors = {
  regular: METRIC_COLORS.orders,
  overtime: METRIC_COLORS.expense,
  hours: METRIC_COLORS.profit,
  fte: METRIC_COLORS.secondary,
};

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`;
};

// Calculate the start date for a pay period N periods back from a reference date
function getPayPeriodStart(referenceStart: string, periodsBack: number): string {
  const date = new Date(referenceStart + "T00:00:00");
  date.setDate(date.getDate() - (periodsBack * 14));
  return date.toISOString().split("T")[0];
}

// Format a pay period label from its start date
function formatPeriodLabel(start: string): string {
  const startDate = new Date(start + "T00:00:00");
  const endDate = new Date(startDate);
  endDate.setDate(endDate.getDate() + 13);

  const startStr = startDate.toLocaleDateString("en-US", { month: "short", day: "numeric" });
  const endStr = endDate.toLocaleDateString("en-US", { month: "short", day: "numeric" });

  return `${startStr} – ${endStr}`;
}

const PayrollMetrics = () => {
  const [historicalData, setHistoricalData] = useState<PayrollMetricsResponse[]>([]);
  const [currentPeriodData, setCurrentPeriodData] = useState<PayrollMetricsResponse | null>(null);
  const [loading, setLoading] = useState<boolean>(true);
  const [error, setError] = useState<string | null>(null);
  const [periodCount, setPeriodCount] = useState<PeriodCountOption>(3);
  const [currentPayPeriodStart, setCurrentPayPeriodStart] = useState<string | null>(null);

  // Fetch historical data for multiple periods
  const fetchHistoricalData = useCallback(async (referenceStart: string, count: PeriodCountOption) => {
    const periodStarts: string[] = [];
    for (let i = 0; i < count; i++) {
      periodStarts.push(getPayPeriodStart(referenceStart, i));
    }

    const results = await Promise.all(
      periodStarts.map(async (start) => {
        try {
          // @ts-expect-error - acotService is a JS file
          const response = await acotService.getPayrollMetrics({ payPeriodStart: start });
          return response as PayrollMetricsResponse;
        } catch {
          return null;
        }
      })
    );

    return results.filter((r): r is PayrollMetricsResponse => r !== null);
  }, []);

  // Initial fetch - get current period first to establish reference
  useEffect(() => {
    let cancelled = false;

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

      try {
        // First, get the current period to establish a reference point
        // @ts-expect-error - acotService is a JS file
        const currentResponse = (await acotService.getPayrollMetrics({})) as PayrollMetricsResponse;

        if (cancelled) return;

        setCurrentPeriodData(currentResponse);

        if (currentResponse.payPeriod?.start) {
          const referenceStart = currentPayPeriodStart || currentResponse.payPeriod.start;
          if (!currentPayPeriodStart) {
            setCurrentPayPeriodStart(currentResponse.payPeriod.start);
          }

          // Fetch historical data
          const historical = await fetchHistoricalData(referenceStart, periodCount);
          if (!cancelled) {
            setHistoricalData(historical);
          }
        }
      } catch (err: unknown) {
        if (!cancelled) {
          let message = "Failed to load payroll 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; };
  }, [currentPayPeriodStart, periodCount, fetchHistoricalData]);

  const isAtCurrentPeriod = !currentPayPeriodStart ||
    currentPayPeriodStart === currentPeriodData?.payPeriod?.start;

  const navigatePeriod = (direction: "prev" | "next") => {
    if (!currentPayPeriodStart) return;

    const currentStart = new Date(currentPayPeriodStart + "T00:00:00");
    const offset = direction === "prev" ? -(14 * periodCount) : (14 * periodCount);
    currentStart.setDate(currentStart.getDate() + offset);
    const newStart = currentStart.toISOString().split("T")[0];

    // If navigating forward would reach or pass the current period, snap to current
    if (direction === "next" && currentPeriodData?.payPeriod?.start && newStart >= currentPeriodData.payPeriod.start) {
      setCurrentPayPeriodStart(null);
      return;
    }

    setCurrentPayPeriodStart(newStart);
  };

  const goToCurrentPeriod = () => {
    setCurrentPayPeriodStart(null);
  };

  // Aggregate stats across all historical periods
  const aggregateStats = useMemo(() => {
    if (historicalData.length === 0) return null;

    const totals = historicalData.reduce(
      (acc, period) => ({
        hours: acc.hours + (period.totals?.hours || 0),
        regularHours: acc.regularHours + (period.totals?.regularHours || 0),
        overtimeHours: acc.overtimeHours + (period.totals?.overtimeHours || 0),
        fte: acc.fte + (period.totals?.fte || 0),
        activeEmployees: acc.activeEmployees + (period.totals?.activeEmployees || 0),
      }),
      { hours: 0, regularHours: 0, overtimeHours: 0, fte: 0, activeEmployees: 0 }
    );

    const avgFte = totals.fte / historicalData.length;
    const avgActiveEmployees = totals.activeEmployees / historicalData.length;
    const avgHoursPerPeriod = totals.hours / historicalData.length;

    // Calculate trend (compare first half to second half)
    const midpoint = Math.floor(historicalData.length / 2);
    const recentPeriods = historicalData.slice(0, midpoint);
    const olderPeriods = historicalData.slice(midpoint);

    const recentAvgHours = recentPeriods.reduce((sum, p) => sum + (p.totals?.hours || 0), 0) / recentPeriods.length;
    const olderAvgHours = olderPeriods.reduce((sum, p) => sum + (p.totals?.hours || 0), 0) / olderPeriods.length;
    const hoursTrend = olderAvgHours > 0 ? ((recentAvgHours - olderAvgHours) / olderAvgHours) * 100 : 0;

    const recentAvgOT = recentPeriods.reduce((sum, p) => sum + (p.totals?.overtimeHours || 0), 0) / recentPeriods.length;
    const olderAvgOT = olderPeriods.reduce((sum, p) => sum + (p.totals?.overtimeHours || 0), 0) / olderPeriods.length;
    const otTrend = olderAvgOT > 0 ? ((recentAvgOT - olderAvgOT) / olderAvgOT) * 100 : 0;

    return {
      totalHours: totals.hours,
      totalRegular: totals.regularHours,
      totalOvertime: totals.overtimeHours,
      avgFte,
      avgActiveEmployees,
      avgHoursPerPeriod,
      hoursTrend,
      otTrend,
      periodCount: historicalData.length,
    };
  }, [historicalData]);

  const cards = useMemo(() => {
    if (!aggregateStats) return [];

    return [
      {
        key: "hours",
        title: "Total Hours",
        value: formatHours(aggregateStats.totalHours),
        description: `${formatHours(aggregateStats.avgHoursPerPeriod)} avg/period`,
        trendValue: aggregateStats.hoursTrend,
        iconColor: "blue" as const,
        tooltip: `Total hours across ${aggregateStats.periodCount} pay periods.`,
      },
      {
        key: "overtime",
        title: "Total Overtime",
        value: formatHours(aggregateStats.totalOvertime),
        description: aggregateStats.totalOvertime > 0
          ? `${formatNumber((aggregateStats.totalOvertime / aggregateStats.totalHours) * 100, 1)}% of total`
          : "No overtime",
        trendValue: aggregateStats.otTrend,
        trendInverted: true,
        iconColor: aggregateStats.totalOvertime > 0 ? "orange" as const : "emerald" as const,
        tooltip: "Total overtime hours across all periods.",
      },
      {
        key: "fte",
        title: "Avg FTE",
        value: formatNumber(aggregateStats.avgFte, 2),
        description: `${formatNumber(aggregateStats.avgActiveEmployees, 0)} avg employees`,
        iconColor: "emerald" as const,
        tooltip: "Average Full-Time Equivalents per period.",
      },
      {
        key: "periods",
        title: "Periods",
        value: String(aggregateStats.periodCount),
        description: `${aggregateStats.periodCount * 2} weeks`,
        iconColor: "purple" as const,
        tooltip: "Number of pay periods shown.",
      },
    ];
  }, [aggregateStats]);

  // Chart data showing trends across periods (or week breakdown for single period)
  const chartData = useMemo(() => {
    if (historicalData.length === 0) return [];

    // Single period: show week-by-week breakdown
    if (historicalData.length === 1) {
      const period = historicalData[0];
      return (period.byWeek || []).map((week, i) => {
        const weekInfo = i === 0 ? period.payPeriod.week1 : period.payPeriod.week2;
        const startDate = new Date((weekInfo?.start || week.start) + "T00:00:00");
        const endDate = new Date((weekInfo?.end || week.end) + "T00:00:00");
        const label = `${startDate.toLocaleDateString("en-US", { month: "short", day: "numeric" })} – ${endDate.toLocaleDateString("en-US", { month: "short", day: "numeric" })}`;
        return {
          label,
          periodStart: week.start,
          regular: week.regular || 0,
          overtime: week.overtime || 0,
          total: week.hours || 0,
          fte: period.totals?.fte || 0,
          employees: period.totals?.activeEmployees || 0,
        };
      });
    }

    // Multiple periods: show period-by-period trend (oldest first, left to right)
    return [...historicalData].reverse().map((period) => ({
      label: formatPeriodLabel(period.payPeriod.start),
      periodStart: period.payPeriod.start,
      regular: period.totals?.regularHours || 0,
      overtime: period.totals?.overtimeHours || 0,
      total: period.totals?.hours || 0,
      fte: period.totals?.fte || 0,
      employees: period.totals?.activeEmployees || 0,
    }));
  }, [historicalData]);

  // Aggregate employee data across ALL displayed periods
  const aggregatedEmployees = useMemo((): AggregatedEmployee[] => {
    if (historicalData.length === 0) return [];

    // Single period: include week-level breakdown
    if (historicalData.length === 1) {
      return (historicalData[0].byEmployee || []).map((emp) => ({
        employeeId: emp.employeeId,
        name: emp.name,
        totalHours: emp.totalHours,
        overtimeHours: emp.overtimeHours,
        regularHours: emp.regularHours,
        periodCount: 1,
        week1Hours: emp.week1Hours,
        week2Hours: emp.week2Hours,
        week1Overtime: emp.week1Overtime,
        week2Overtime: emp.week2Overtime,
      }));
    }

    // Multiple periods: aggregate across all periods
    const employeeMap = new Map<number, AggregatedEmployee>();

    historicalData.forEach((period) => {
      (period.byEmployee || []).forEach((emp) => {
        const existing = employeeMap.get(emp.employeeId);
        if (existing) {
          existing.totalHours += emp.totalHours;
          existing.overtimeHours += emp.overtimeHours;
          existing.regularHours += emp.regularHours;
          existing.periodCount += 1;
        } else {
          employeeMap.set(emp.employeeId, {
            employeeId: emp.employeeId,
            name: emp.name,
            totalHours: emp.totalHours,
            overtimeHours: emp.overtimeHours,
            regularHours: emp.regularHours,
            periodCount: 1,
          });
        }
      });
    });

    return Array.from(employeeMap.values());
  }, [historicalData]);

  const hasData = chartData.length > 0;

  const headerActions = !error ? (
    <div className="flex items-center gap-2 flex-wrap">
      <Select
        value={String(periodCount)}
        onValueChange={(value) => {
          setPeriodCount(Number(value) as PeriodCountOption);
          setCurrentPayPeriodStart(null);
        }}
        disabled={loading}
      >
        <SelectTrigger className="h-9 w-[110px]">
          <SelectValue />
        </SelectTrigger>
        <SelectContent>
          {PERIOD_COUNT_OPTIONS.map((option) => (
            <SelectItem key={option.value} value={String(option.value)}>
              {option.label}
            </SelectItem>
          ))}
        </SelectContent>
      </Select>

      <div className="flex items-center gap-1">
        <Button
          variant="outline"
          size="icon"
          className="h-9 w-9"
          onClick={() => navigatePeriod("prev")}
          disabled={loading}
        >
          <ChevronLeft className="h-4 w-4" />
        </Button>
        <Button
          variant="outline"
          className="h-9 px-3 min-w-[120px]"
          onClick={goToCurrentPeriod}
          disabled={loading || isAtCurrentPeriod}
        >
          <Calendar className="h-4 w-4 mr-2" />
          {loading ? "Loading..." : "Current"}
        </Button>
        <Button
          variant="outline"
          size="icon"
          className="h-9 w-9"
          onClick={() => navigatePeriod("next")}
          disabled={loading || isAtCurrentPeriod}
        >
          <ChevronRight className="h-4 w-4" />
        </Button>
      </div>
    </div>
  ) : null;

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

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

        {loading ? (
          <div className="flex flex-col lg:flex-row gap-6">
            <div className="w-full lg:w-[65%]">
              <ChartSkeleton type="bar" height="md" withCard={false} />
            </div>
            <div className="w-full lg:w-[35%]">
              <EmployeeTableSkeleton />
            </div>
          </div>
        ) : error ? (
          <DashboardErrorState error={`Failed to load payroll data: ${error}`} className="mx-0 my-0" />
        ) : !hasData ? (
          <DashboardEmptyState
            icon={Clock}
            title="No payroll data available"
            description="Try selecting a different pay period"
          />
        ) : (
          <div className="flex flex-col lg:flex-row gap-6">
            <div className={`h-[300px] w-full lg:w-[65%] ${CARD_STYLES.base} rounded-lg p-0 relative`}>
              <ResponsiveContainer width="100%" height="100%">
                <ComposedChart data={chartData} margin={{ top: 20, right: 20, left: 20, bottom: 5 }}>
                  <CartesianGrid strokeDasharray="3 3" className="stroke-muted" />
                  <XAxis
                    dataKey="label"
                    className="text-xs text-muted-foreground"
                    tick={{ fill: "currentColor", fontSize: 10 }}
                    angle={-45}
                    textAnchor="end"
                    height={60}
                    interval={0}
                  />
                  <YAxis
                    yAxisId="hours"
                    tickFormatter={(value: number) => `${value}h`}
                    className="text-xs text-muted-foreground"
                    tick={{ fill: "currentColor" }}
                  />
                  <YAxis
                    yAxisId="fte"
                    orientation="right"
                    tickFormatter={(value: number) => value.toFixed(1)}
                    className="text-xs text-muted-foreground"
                    tick={{ fill: "currentColor" }}
                  />
                  <Tooltip content={<PayrollTrendTooltip />} />
                  <Legend />
                  <Bar
                    yAxisId="hours"
                    dataKey="regular"
                    name="Regular Hours"
                    stackId="hours"
                    fill={chartColors.regular}
                  />
                  <Bar
                    yAxisId="hours"
                    dataKey="overtime"
                    name="Overtime"
                    stackId="hours"
                    fill={chartColors.overtime}
                  />
                  <Line
                    yAxisId="fte"
                    type="monotone"
                    dataKey="fte"
                    name="FTE"
                    stroke={chartColors.fte}
                    strokeWidth={2}
                    dot={{ fill: chartColors.fte, r: 3 }}
                  />
                </ComposedChart>
              </ResponsiveContainer>
            </div>
            <div className="w-full lg:w-[35%]">
              <PayrollEmployeeSummary
                employees={aggregatedEmployees}
                periodCount={historicalData.length}
              />
            </div>
          </div>
        )}


      </CardContent>
    </Card>
  );
};

type PayrollStatCardConfig = {
  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 = {
  hours: Clock,
  overtime: AlertTriangle,
  fte: Users,
  periods: TrendingUp,
} as const;

function PayrollStatGrid({ cards }: { cards: PayrollStatCardConfig[] }) {
  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>
  );
}

type TrendChartPoint = {
  label: string;
  periodStart: string;
  regular: number;
  overtime: number;
  total: number;
  fte: number;
  employees: number;
};

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

  const data = payload[0]?.payload as TrendChartPoint | undefined;
  if (!data) return null;

  return (
    <div className={TOOLTIP_STYLES.container}>
      <p className={TOOLTIP_STYLES.header}>{label}</p>
      <div className={TOOLTIP_STYLES.content}>
        <div className={TOOLTIP_STYLES.row}>
          <div className={TOOLTIP_STYLES.rowLabel}>
            <span className={TOOLTIP_STYLES.dot} style={{ backgroundColor: chartColors.regular }} />
            <span className={TOOLTIP_STYLES.name}>Regular Hours</span>
          </div>
          <span className={TOOLTIP_STYLES.value}>{formatHours(data.regular)}</span>
        </div>
        {data.overtime > 0 && (
          <div className={TOOLTIP_STYLES.row}>
            <div className={TOOLTIP_STYLES.rowLabel}>
              <span className={TOOLTIP_STYLES.dot} style={{ backgroundColor: chartColors.overtime }} />
              <span className={TOOLTIP_STYLES.name}>Overtime</span>
            </div>
            <span className={TOOLTIP_STYLES.value}>{formatHours(data.overtime)}</span>
          </div>
        )}
        <div className={`${TOOLTIP_STYLES.row} border-t border-border/50 pt-1 mt-1`}>
          <div className={TOOLTIP_STYLES.rowLabel}>
            <span className={TOOLTIP_STYLES.name}>Total Hours</span>
          </div>
          <span className={`${TOOLTIP_STYLES.value} font-semibold`}>{formatHours(data.total)}</span>
        </div>
        <div className={TOOLTIP_STYLES.row}>
          <div className={TOOLTIP_STYLES.rowLabel}>
            <span className={TOOLTIP_STYLES.dot} style={{ backgroundColor: chartColors.fte }} />
            <span className={TOOLTIP_STYLES.name}>FTE</span>
          </div>
          <span className={TOOLTIP_STYLES.value}>{formatNumber(data.fte, 2)}</span>
        </div>
        <div className={TOOLTIP_STYLES.row}>
          <div className={TOOLTIP_STYLES.rowLabel}>
            <span className={TOOLTIP_STYLES.name}>Employees</span>
          </div>
          <span className={TOOLTIP_STYLES.value}>{data.employees}</span>
        </div>
      </div>
    </div>
  );
};

function EmployeeTableSkeleton() {
  return (
    <div className={`h-[300px] 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">
        {Array.from({ length: 8 }).map((_, i) => (
          <div key={i} className="flex items-center gap-3 px-2 py-1.5">
            <div className="h-3 w-24 bg-muted rounded animate-pulse" />
            <div className="flex-1" />
            <div className="h-3 w-12 bg-muted rounded animate-pulse" />
            <div className="h-3 w-12 bg-muted rounded animate-pulse" />
          </div>
        ))}
      </div>
    </div>
  );
}

type AggregatedEmployee = {
  employeeId: number;
  name: string;
  totalHours: number;
  overtimeHours: number;
  regularHours: number;
  periodCount: number;
  week1Hours?: number;
  week2Hours?: number;
  week1Overtime?: number;
  week2Overtime?: number;
};

function PayrollEmployeeSummary({
  employees,
  periodCount,
  maxRows = 10
}: {
  employees: AggregatedEmployee[];
  periodCount: number;
  maxRows?: number;
}) {
  const sortedEmployees = useMemo(() => {
    return [...employees]
      .sort((a, b) => b.totalHours - a.totalHours)
      .slice(0, maxRows);
  }, [employees, maxRows]);

  const hasWeekData = periodCount === 1 && employees.some((e) => e.week1Hours != null);

  if (sortedEmployees.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>
    );
  }

  const periodLabel = periodCount === 1
    ? "1 period"
    : `${periodCount} periods`;

  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">
          Employee Summary
          <span className="text-muted-foreground font-normal ml-1">({periodLabel})</span>
        </h4>
      </div>
      <div className="flex-1 overflow-auto">
        <Table>
          <TableHeader>
            <TableRow className="hover:bg-transparent">
              <TableHead className="h-8 text-xs px-3">Name</TableHead>
              {hasWeekData ? (
                <>
                  <TableHead className="h-8 text-xs px-2 text-right">Wk 1</TableHead>
                  <TableHead className="h-8 text-xs px-2 text-right">Wk 2</TableHead>
                </>
              ) : (
                <TableHead className="h-8 text-xs px-2 text-right">Regular</TableHead>
              )}
              <TableHead className="h-8 text-xs px-2 text-right">Total</TableHead>
              <TableHead className="h-8 text-xs px-2 text-right">OT</TableHead>
              {periodCount > 1 && (
                <TableHead className="h-8 text-xs px-2 text-right">Avg/Per</TableHead>
              )}
            </TableRow>
          </TableHeader>
          <TableBody>
            {sortedEmployees.map((emp) => (
              <TableRow
                key={emp.employeeId}
                className={emp.overtimeHours > 0 ? "bg-orange-500/5" : ""}
              >
                <TableCell className="py-1.5 px-3 text-xs font-medium truncate max-w-[120px]">
                  {emp.name}
                </TableCell>
                {hasWeekData ? (
                  <>
                    <TableCell className="py-1.5 px-2 text-xs text-right">
                      <span className={emp.week1Overtime && emp.week1Overtime > 0 ? "text-orange-600 dark:text-orange-400 font-medium" : "text-muted-foreground"}>
                        {formatHours(emp.week1Hours || 0)}
                      </span>
                    </TableCell>
                    <TableCell className="py-1.5 px-2 text-xs text-right">
                      <span className={emp.week2Overtime && emp.week2Overtime > 0 ? "text-orange-600 dark:text-orange-400 font-medium" : "text-muted-foreground"}>
                        {formatHours(emp.week2Hours || 0)}
                      </span>
                    </TableCell>
                  </>
                ) : (
                  <TableCell className="py-1.5 px-2 text-xs text-right text-muted-foreground">
                    {formatHours(emp.regularHours)}
                  </TableCell>
                )}
                <TableCell className="py-1.5 px-2 text-xs text-right font-medium">
                  {formatHours(emp.totalHours)}
                </TableCell>
                <TableCell className="py-1.5 px-2 text-xs text-right">
                  {emp.overtimeHours > 0 ? (
                    <span className="text-orange-600 dark:text-orange-400 font-medium">
                      {formatHours(emp.overtimeHours)}
                    </span>
                  ) : (
                    <span className="text-muted-foreground">—</span>
                  )}
                </TableCell>
                {periodCount > 1 && (
                  <TableCell className="py-1.5 px-2 text-xs text-right text-muted-foreground">
                    {formatHours(emp.totalHours / emp.periodCount)}
                  </TableCell>
                )}
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </div>
      {employees.length > maxRows && (
        <div className="p-2 border-t text-center flex-none">
          <span className="text-xs text-muted-foreground">
            +{employees.length - maxRows} more employees
          </span>
        </div>
      )}
    </div>
  );
}

export default PayrollMetrics;
