"use client";

import { type StatisticsTimeFrame, StatisticsTimeFrameSchema } from "@shared";
import { format } from "date-fns";
import { Calendar as CalendarIcon, Clock } from "lucide-react";
import { useRouter, useSearchParams } from "next/navigation";
import { useCallback, useEffect, useMemo, useState } from "react";
import { CartesianGrid, Line, LineChart, XAxis, YAxis } from "recharts";
import { useSetCostsAction } from "@/app/llm/(costs)/layout";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
  type ChartConfig,
  ChartContainer,
  ChartLegend,
  ChartLegendContent,
  ChartTooltip,
  ChartTooltipContent,
} from "@/components/ui/chart";
import { CustomDateTimeRangeDialog } from "@/components/ui/custom-date-time-range-dialog";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import {
  useCostSavingsStatistics,
  useModelStatistics,
  useProfileStatistics,
  useTeamStatistics,
} from "@/lib/statistics.query";

/**
 * Reusable tooltip component for cost charts.
 * Shows a color dot indicator and formatted cost value for each data series.
 */
const CostChartTooltip = (
  <ChartTooltipContent
    indicator="dot"
    formatter={(value, _name, item) => (
      <>
        <div
          className="shrink-0 rounded-[2px] h-2.5 w-2.5"
          style={{
            backgroundColor: item.color || item.fill,
          }}
        />
        <span className="text-foreground font-mono font-medium tabular-nums">
          ${Number(value).toFixed(2)}
        </span>
      </>
    )}
  />
);

interface ChartContainerWrapperProps {
  config: ChartConfig;
  data: Record<string, string | number>[];
  emptyMessage?: string;
  children: React.ReactNode;
}

const ChartContainerWrapper = ({
  config,
  data,
  emptyMessage = "No data available",
  children,
}: ChartContainerWrapperProps) => (
  <ChartContainer config={config} className="aspect-auto h-80 w-full relative">
    {data.length > 0 ? (
      children
    ) : (
      <div className="absolute inset-0 flex items-center justify-center text-muted-foreground">
        {emptyMessage}
      </div>
    )}
  </ChartContainer>
);

const TIMEFRAME_STORAGE_KEY = "cost-statistics-timeframe";
const STATISTICS_TABLE_MAX_HEIGHT_CLASS = "max-h-[280px]";

export default function StatisticsPage() {
  const router = useRouter();
  const setActionButton = useSetCostsAction();
  const searchParams = useSearchParams();

  const [timeframe, setTimeframe] = useState<StatisticsTimeFrame>("1h");
  const [customFrom, setCustomFrom] = useState<Date | undefined>();
  const [customTo, setCustomTo] = useState<Date | undefined>();
  const [isCustomDialogOpen, setIsCustomDialogOpen] = useState(false);

  // Statistics data fetching hooks
  const { data: teamStatistics = [] } = useTeamStatistics({
    timeframe,
  });
  const { data: agentStatistics = [] } = useProfileStatistics({
    timeframe,
  });
  const { data: modelStatistics = [] } = useModelStatistics({
    timeframe,
  });
  const { data: costSavingsData } = useCostSavingsStatistics({
    timeframe,
  });

  /**
   * Initialize from URL parameters or localStorage
   */
  useEffect(() => {
    const urlTimeframe = searchParams.get("timeframe");
    const storedTimeframe = localStorage.getItem(TIMEFRAME_STORAGE_KEY);

    // URL params take precedence, then localStorage, then default
    const { success, data } = StatisticsTimeFrameSchema.safeParse(
      urlTimeframe ?? storedTimeframe,
    );
    if (success) {
      setTimeframe(data);
      const customRange = parseCustomTimeframe(data);
      setCustomFrom(customRange?.from);
      setCustomTo(customRange?.to);
    } else {
      setTimeframe("1h");
      setCustomFrom(undefined);
      setCustomTo(undefined);
    }
  }, [searchParams]);

  // Update URL when timeframe changes
  const updateURL = useCallback(
    (newTimeframe?: string) => {
      const params = new URLSearchParams(searchParams);

      if (newTimeframe !== undefined) {
        params.set("timeframe", newTimeframe);
      }

      router.push(`/llm/costs?${params.toString()}`, {
        scroll: false,
      });
    },
    [router, searchParams],
  );

  const handleTimeframeChange = useCallback(
    (tf: StatisticsTimeFrame) => {
      setTimeframe(tf);
      localStorage.setItem(TIMEFRAME_STORAGE_KEY, tf);
      updateURL(tf);
    },
    [updateURL],
  );

  const handleCustomTimeframe = useCallback(() => {
    if (!customFrom || !customTo) return;

    const fromDateTime = new Date(customFrom);
    const toDateTime = new Date(customTo);
    toDateTime.setSeconds(59, 999);

    const customValue =
      `custom:${fromDateTime.toISOString()}_${toDateTime.toISOString()}` as const;
    handleTimeframeChange(customValue);
    setIsCustomDialogOpen(false);
  }, [customFrom, customTo, handleTimeframeChange]);

  const getTimeframeDisplay = useCallback((tf: StatisticsTimeFrame) => {
    if (tf.startsWith("custom:")) {
      const value = tf.replace("custom:", "");
      const [fromDate, toDate] = value.split("_");
      const fromDateTime = new Date(fromDate);
      const toDateTime = new Date(toDate);

      const hasCustomTime =
        fromDateTime.getHours() !== 0 ||
        fromDateTime.getMinutes() !== 0 ||
        toDateTime.getHours() !== 23 ||
        toDateTime.getMinutes() !== 59;

      if (hasCustomTime) {
        return `${format(fromDateTime, "MMM d, HH:mm")} - ${format(toDateTime, "MMM d, HH:mm")}`;
      } else {
        return `${format(fromDateTime, "MMM d")} - ${format(toDateTime, "MMM d")}`;
      }
    }
    switch (tf) {
      case "1h":
        return "hour";
      case "24h":
        return "24 hours";
      case "7d":
        return "7 days";
      case "30d":
        return "30 days";
      case "90d":
        return "90 days";
      case "12m":
        return "12 months";
      case "all":
        return "";
      default:
        return tf;
    }
  }, []);

  // Format timestamp for display based on timeframe
  const formatTimestamp = useCallback(
    (timestamp: string) => {
      const date = new Date(timestamp);
      if (timeframe === "1h" || timeframe === "24h") {
        return format(date, "HH:mm");
      }
      return format(date, "MMM d");
    },
    [timeframe],
  );

  // Convert team statistics to recharts format
  const teamChartData = useMemo(() => {
    if (teamStatistics.length === 0) return [];

    const allTimestamps = [
      ...new Set(
        teamStatistics.flatMap((stat) =>
          stat.timeSeries.map((point) => point.timestamp),
        ),
      ),
    ].sort();

    return allTimestamps.map((timestamp) => {
      const dataPoint: Record<string, string | number> = {
        timestamp,
        label: formatTimestamp(timestamp),
      };
      teamStatistics.slice(0, 5).forEach((team) => {
        const point = team.timeSeries.find((p) => p.timestamp === timestamp);
        dataPoint[team.teamId] = point ? point.value : 0;
      });
      return dataPoint;
    });
  }, [teamStatistics, formatTimestamp]);

  const teamChartConfig = useMemo(() => {
    const config: ChartConfig = {};
    teamStatistics.slice(0, 5).forEach((team, index) => {
      config[team.teamId] = {
        label: team.teamName,
        color: `var(--chart-${index + 1})`,
      };
    });
    return config;
  }, [teamStatistics]);

  // Filter agent statistics by type
  const chatAgentStatistics = useMemo(
    () => agentStatistics.filter((stat) => stat.agentType === "agent"),
    [agentStatistics],
  );
  const llmProxyStatistics = useMemo(
    () => agentStatistics.filter((stat) => stat.agentType === "llm_proxy"),
    [agentStatistics],
  );

  // Convert agent statistics to recharts format
  const agentChartData = useMemo(() => {
    if (chatAgentStatistics.length === 0) return [];

    const allTimestamps = [
      ...new Set(
        chatAgentStatistics.flatMap((stat) =>
          stat.timeSeries.map((point) => point.timestamp),
        ),
      ),
    ].sort();

    return allTimestamps.map((timestamp) => {
      const dataPoint: Record<string, string | number> = {
        timestamp,
        label: formatTimestamp(timestamp),
      };
      chatAgentStatistics.slice(0, 5).forEach((agent) => {
        const point = agent.timeSeries.find((p) => p.timestamp === timestamp);
        dataPoint[agent.agentId] = point ? point.value : 0;
      });
      return dataPoint;
    });
  }, [chatAgentStatistics, formatTimestamp]);

  const agentChartConfig = useMemo(() => {
    const config: ChartConfig = {};
    chatAgentStatistics.slice(0, 5).forEach((agent, index) => {
      config[agent.agentId] = {
        label: agent.agentName,
        color: `var(--chart-${index + 1})`,
      };
    });
    return config;
  }, [chatAgentStatistics]);

  // Convert LLM proxy statistics to recharts format
  const llmProxyChartData = useMemo(() => {
    if (llmProxyStatistics.length === 0) return [];

    const allTimestamps = [
      ...new Set(
        llmProxyStatistics.flatMap((stat) =>
          stat.timeSeries.map((point) => point.timestamp),
        ),
      ),
    ].sort();

    return allTimestamps.map((timestamp) => {
      const dataPoint: Record<string, string | number> = {
        timestamp,
        label: formatTimestamp(timestamp),
      };
      llmProxyStatistics.slice(0, 5).forEach((agent) => {
        const point = agent.timeSeries.find((p) => p.timestamp === timestamp);
        dataPoint[agent.agentId] = point ? point.value : 0;
      });
      return dataPoint;
    });
  }, [llmProxyStatistics, formatTimestamp]);

  const llmProxyChartConfig = useMemo(() => {
    const config: ChartConfig = {};
    llmProxyStatistics.slice(0, 5).forEach((agent, index) => {
      config[agent.agentId] = {
        label: agent.agentName,
        color: `var(--chart-${index + 1})`,
      };
    });
    return config;
  }, [llmProxyStatistics]);

  // Convert model statistics to recharts format
  const modelChartData = useMemo(() => {
    if (modelStatistics.length === 0) return [];

    const allTimestamps = [
      ...new Set(
        modelStatistics.flatMap((stat) =>
          stat.timeSeries.map((point) => point.timestamp),
        ),
      ),
    ].sort();

    return allTimestamps.map((timestamp) => {
      const dataPoint: Record<string, string | number> = {
        timestamp,
        label: formatTimestamp(timestamp),
      };
      modelStatistics.slice(0, 5).forEach((model) => {
        const point = model.timeSeries.find((p) => p.timestamp === timestamp);
        dataPoint[model.model] = point ? point.value : 0;
      });
      return dataPoint;
    });
  }, [modelStatistics, formatTimestamp]);

  const modelChartConfig = useMemo(() => {
    const config: ChartConfig = {};
    modelStatistics.slice(0, 5).forEach((model, index) => {
      config[model.model] = {
        label: model.model,
        color: `var(--chart-${index + 1})`,
      };
    });
    return config;
  }, [modelStatistics]);

  // Cost savings chart data
  const costSavingsChartData = useMemo(() => {
    if (!costSavingsData || costSavingsData.timeSeries.length === 0) return [];

    return costSavingsData.timeSeries.map((point) => ({
      timestamp: point.timestamp,
      label: formatTimestamp(point.timestamp),
      nonOptimized: point.baselineCost,
      actual: point.actualCost,
    }));
  }, [costSavingsData, formatTimestamp]);

  const costSavingsChartConfig: ChartConfig = {
    nonOptimized: {
      label: "Non-Optimized Cost",
      color: "var(--chart-4)",
    },
    actual: {
      label: "Actual Cost",
      color: "var(--chart-2)",
    },
  };

  // Savings breakdown chart data
  const savingsBreakdownChartData = useMemo(() => {
    if (!costSavingsData || costSavingsData.timeSeries.length === 0) return [];

    return costSavingsData.timeSeries.map((point) => ({
      timestamp: point.timestamp,
      label: formatTimestamp(point.timestamp),
      optimization: point.optimizationSavings,
      compression: point.toonSavings,
    }));
  }, [costSavingsData, formatTimestamp]);

  const savingsBreakdownChartConfig: ChartConfig = {
    optimization: {
      label: "Optimization Rules Savings",
      color: "var(--chart-1)",
    },
    compression: {
      label: "Tool Compression Savings",
      color: "var(--chart-5)",
    },
  };

  // Sort statistics by cost for table display
  const sortedTeamStatistics = useMemo(
    () => [...teamStatistics].sort((a, b) => b.cost - a.cost),
    [teamStatistics],
  );
  const sortedChatAgentStatistics = useMemo(
    () => [...chatAgentStatistics].sort((a, b) => b.cost - a.cost),
    [chatAgentStatistics],
  );
  const sortedLlmProxyStatistics = useMemo(
    () => [...llmProxyStatistics].sort((a, b) => b.cost - a.cost),
    [llmProxyStatistics],
  );
  const sortedModelStatistics = useMemo(
    () => [...modelStatistics].sort((a, b) => b.cost - a.cost),
    [modelStatistics],
  );

  useEffect(() => {
    setActionButton(
      <div className="flex gap-2">
        <Select
          value={timeframe.startsWith("custom:") ? "custom" : timeframe}
          onValueChange={(value) => {
            if (value === "custom") {
              setIsCustomDialogOpen(true);
            } else {
              handleTimeframeChange(value as StatisticsTimeFrame);
            }
          }}
        >
          <SelectTrigger className="w-[320px]">
            <CalendarIcon className="mr-2 h-4 w-4" />
            <SelectValue>
              {timeframe.startsWith("custom:")
                ? `Custom: ${getTimeframeDisplay(timeframe)}`
                : timeframe === "all"
                  ? "All time"
                  : `Last ${getTimeframeDisplay(timeframe)}`}
            </SelectValue>
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="5m">5 Minutes</SelectItem>
            <SelectItem value="15m">15 Minutes</SelectItem>
            <SelectItem value="30m">30 Minutes</SelectItem>
            <SelectItem value="1h">Last hour</SelectItem>
            <SelectItem value="24h">Last 24 hours</SelectItem>
            <SelectItem value="7d">Last 7 days</SelectItem>
            <SelectItem value="30d">Last 30 days</SelectItem>
            <SelectItem value="90d">Last 90 days</SelectItem>
            <SelectItem value="12m">Last 12 months</SelectItem>
            <SelectItem value="all">All time</SelectItem>
            <SelectItem value="custom">
              <Clock className="mr-2 h-4 w-4 inline" />
              Custom timeframe...
            </SelectItem>
          </SelectContent>
        </Select>

        {timeframe.startsWith("custom:") && (
          <Button
            variant="outline"
            onClick={() => setIsCustomDialogOpen(true)}
            className="h-9 flex items-center gap-1 px-3"
          >
            <Clock className="h-4 w-4" />
            Edit
          </Button>
        )}
      </div>,
    );

    return () => setActionButton(null);
  }, [getTimeframeDisplay, handleTimeframeChange, setActionButton, timeframe]);

  return (
    <div className="space-y-6">
      <CustomDateTimeRangeDialog
        open={isCustomDialogOpen}
        onOpenChange={setIsCustomDialogOpen}
        startDate={customFrom}
        endDate={customTo}
        onStartDateChange={setCustomFrom}
        onEndDateChange={setCustomTo}
        onApply={handleCustomTimeframe}
        title="Custom timeframe"
        description="Set a custom time period for the statistics view."
      />

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <Card>
          <CardHeader>
            <CardTitle>Costs</CardTitle>
          </CardHeader>
          <CardContent>
            <ChartContainerWrapper
              config={costSavingsChartConfig}
              data={costSavingsChartData}
            >
              <LineChart
                accessibilityLayer
                data={costSavingsChartData}
                margin={{ top: 12, left: 12, right: 12 }}
              >
                <CartesianGrid vertical={false} />
                <XAxis
                  dataKey="label"
                  tickLine={false}
                  axisLine={false}
                  tickMargin={8}
                />
                <YAxis
                  tickLine={false}
                  axisLine={false}
                  tickMargin={8}
                  tickFormatter={(value) => `$${value}`}
                />
                <ChartTooltip content={CostChartTooltip} />
                <ChartLegend content={<ChartLegendContent />} />
                <Line
                  dataKey="nonOptimized"
                  type="monotone"
                  stroke="var(--color-nonOptimized)"
                  strokeWidth={2}
                  dot={{
                    strokeWidth: 0,
                    r: 3,
                    fill: "var(--color-nonOptimized)",
                  }}
                  activeDot={{ strokeWidth: 0, r: 5 }}
                />
                <Line
                  dataKey="actual"
                  type="monotone"
                  stroke="var(--color-actual)"
                  strokeWidth={2}
                  dot={{ strokeWidth: 0, r: 3, fill: "var(--color-actual)" }}
                  activeDot={{ strokeWidth: 0, r: 5 }}
                />
              </LineChart>
            </ChartContainerWrapper>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>Cost Savings</CardTitle>
          </CardHeader>
          <CardContent>
            <ChartContainerWrapper
              config={savingsBreakdownChartConfig}
              data={savingsBreakdownChartData}
            >
              <LineChart
                accessibilityLayer
                data={savingsBreakdownChartData}
                margin={{ top: 12, left: 12, right: 12 }}
              >
                <CartesianGrid vertical={false} />
                <XAxis
                  dataKey="label"
                  tickLine={false}
                  axisLine={false}
                  tickMargin={8}
                />
                <YAxis
                  tickLine={false}
                  axisLine={false}
                  tickMargin={8}
                  tickFormatter={(value) => `$${value}`}
                />
                <ChartTooltip content={CostChartTooltip} />
                <ChartLegend content={<ChartLegendContent />} />
                <Line
                  dataKey="optimization"
                  type="monotone"
                  stroke="var(--color-optimization)"
                  strokeWidth={2}
                  dot={{
                    strokeWidth: 0,
                    r: 3,
                    fill: "var(--color-optimization)",
                  }}
                  activeDot={{ strokeWidth: 0, r: 5 }}
                />
                <Line
                  dataKey="compression"
                  type="monotone"
                  stroke="var(--color-compression)"
                  strokeWidth={2}
                  dot={{
                    strokeWidth: 0,
                    r: 3,
                    fill: "var(--color-compression)",
                  }}
                  activeDot={{ strokeWidth: 0, r: 5 }}
                />
              </LineChart>
            </ChartContainerWrapper>
          </CardContent>
        </Card>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>Teams</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="space-y-4">
            <div className="space-y-3">
              <ChartContainerWrapper
                config={teamChartConfig}
                data={teamChartData}
                emptyMessage="No team data available"
              >
                <LineChart
                  accessibilityLayer
                  data={teamChartData}
                  margin={{ top: 12, left: 12, right: 12 }}
                >
                  <CartesianGrid vertical={false} />
                  <XAxis
                    dataKey="label"
                    tickLine={false}
                    axisLine={false}
                    tickMargin={8}
                  />
                  <YAxis
                    tickLine={false}
                    axisLine={false}
                    tickMargin={8}
                    tickFormatter={(value) => `$${value}`}
                  />
                  <ChartTooltip content={CostChartTooltip} />
                  <ChartLegend content={<ChartLegendContent />} />
                  {teamStatistics.slice(0, 5).map((team) => (
                    <Line
                      key={team.teamId}
                      dataKey={team.teamId}
                      type="monotone"
                      stroke={`var(--color-${team.teamId})`}
                      strokeWidth={2}
                      dot={{
                        strokeWidth: 0,
                        r: 3,
                        fill: `var(--color-${team.teamId})`,
                      }}
                      activeDot={{ strokeWidth: 0, r: 5 }}
                    />
                  ))}
                </LineChart>
              </ChartContainerWrapper>
              {teamStatistics.length > 5 && (
                <p className="text-xs text-muted-foreground text-center mt-2">
                  Chart shows top 5 by cost
                </p>
              )}
            </div>

            <StatisticsTablePanel>
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead className="bg-card sticky top-0 z-10">
                      Team Name
                    </TableHead>
                    <TableHead className="bg-card sticky top-0 z-10">
                      Members
                    </TableHead>
                    <TableHead className="bg-card sticky top-0 z-10">
                      Profiles
                    </TableHead>
                    <TableHead className="bg-card sticky top-0 z-10">
                      Requests
                    </TableHead>
                    <TableHead className="bg-card sticky top-0 z-10">
                      Tokens
                    </TableHead>
                    <TableHead className="bg-card sticky top-0 z-10 text-right">
                      Cost
                    </TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {sortedTeamStatistics.length === 0 ? (
                    <TableRow>
                      <TableCell
                        colSpan={6}
                        className="text-center py-8 text-muted-foreground"
                      >
                        No team data available for the selected timeframe
                      </TableCell>
                    </TableRow>
                  ) : (
                    sortedTeamStatistics.map((team) => (
                      <TableRow key={team.teamId}>
                        <TableCell className="font-medium">
                          {team.teamName}
                        </TableCell>
                        <TableCell>{team.members}</TableCell>
                        <TableCell>{team.agents}</TableCell>
                        <TableCell>{team.requests.toLocaleString()}</TableCell>
                        <TableCell>
                          {(
                            team.inputTokens + team.outputTokens
                          ).toLocaleString()}
                        </TableCell>
                        <TableCell className="text-right">
                          ${team.cost.toFixed(2)}
                        </TableCell>
                      </TableRow>
                    ))
                  )}
                </TableBody>
              </Table>
            </StatisticsTablePanel>
          </div>
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle>Agents</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="space-y-4">
            <div className="space-y-3">
              <ChartContainerWrapper
                config={agentChartConfig}
                data={agentChartData}
                emptyMessage="No agent data available"
              >
                <LineChart
                  accessibilityLayer
                  data={agentChartData}
                  margin={{ top: 12, left: 12, right: 12 }}
                >
                  <CartesianGrid vertical={false} />
                  <XAxis
                    dataKey="label"
                    tickLine={false}
                    axisLine={false}
                    tickMargin={8}
                  />
                  <YAxis
                    tickLine={false}
                    axisLine={false}
                    tickMargin={8}
                    tickFormatter={(value) => `$${value}`}
                  />
                  <ChartTooltip content={CostChartTooltip} />
                  <ChartLegend content={<ChartLegendContent />} />
                  {chatAgentStatistics.slice(0, 5).map((agent) => (
                    <Line
                      key={agent.agentId}
                      dataKey={agent.agentId}
                      type="monotone"
                      stroke={`var(--color-${agent.agentId})`}
                      strokeWidth={2}
                      dot={{
                        strokeWidth: 0,
                        r: 3,
                        fill: `var(--color-${agent.agentId})`,
                      }}
                      activeDot={{ strokeWidth: 0, r: 5 }}
                    />
                  ))}
                </LineChart>
              </ChartContainerWrapper>
              {chatAgentStatistics.length > 5 && (
                <p className="text-xs text-muted-foreground text-center mt-2">
                  Chart shows top 5 by cost
                </p>
              )}
            </div>

            <StatisticsTablePanel>
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead className="bg-card sticky top-0 z-10">
                      Name
                    </TableHead>
                    <TableHead className="bg-card sticky top-0 z-10">
                      Team
                    </TableHead>
                    <TableHead className="bg-card sticky top-0 z-10">
                      Requests
                    </TableHead>
                    <TableHead className="bg-card sticky top-0 z-10">
                      Tokens
                    </TableHead>
                    <TableHead className="bg-card sticky top-0 z-10 text-right">
                      Cost
                    </TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {sortedChatAgentStatistics.length === 0 ? (
                    <TableRow>
                      <TableCell
                        colSpan={5}
                        className="text-center py-8 text-muted-foreground"
                      >
                        No agent data available for the selected timeframe
                      </TableCell>
                    </TableRow>
                  ) : (
                    sortedChatAgentStatistics.map((agent) => (
                      <TableRow key={agent.agentId}>
                        <TableCell className="font-medium">
                          {agent.agentName}
                        </TableCell>
                        <TableCell>{agent.teamName}</TableCell>
                        <TableCell>{agent.requests.toLocaleString()}</TableCell>
                        <TableCell>
                          {(
                            agent.inputTokens + agent.outputTokens
                          ).toLocaleString()}
                        </TableCell>
                        <TableCell className="text-right">
                          ${agent.cost.toFixed(2)}
                        </TableCell>
                      </TableRow>
                    ))
                  )}
                </TableBody>
              </Table>
            </StatisticsTablePanel>
          </div>
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle>LLM Proxies</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="space-y-4">
            <div className="space-y-3">
              <ChartContainerWrapper
                config={llmProxyChartConfig}
                data={llmProxyChartData}
                emptyMessage="No LLM proxy data available"
              >
                <LineChart
                  accessibilityLayer
                  data={llmProxyChartData}
                  margin={{ top: 12, left: 12, right: 12 }}
                >
                  <CartesianGrid vertical={false} />
                  <XAxis
                    dataKey="label"
                    tickLine={false}
                    axisLine={false}
                    tickMargin={8}
                  />
                  <YAxis
                    tickLine={false}
                    axisLine={false}
                    tickMargin={8}
                    tickFormatter={(value) => `$${value}`}
                  />
                  <ChartTooltip content={CostChartTooltip} />
                  <ChartLegend content={<ChartLegendContent />} />
                  {llmProxyStatistics.slice(0, 5).map((proxy) => (
                    <Line
                      key={proxy.agentId}
                      dataKey={proxy.agentId}
                      type="monotone"
                      stroke={`var(--color-${proxy.agentId})`}
                      strokeWidth={2}
                      dot={{
                        strokeWidth: 0,
                        r: 3,
                        fill: `var(--color-${proxy.agentId})`,
                      }}
                      activeDot={{ strokeWidth: 0, r: 5 }}
                    />
                  ))}
                </LineChart>
              </ChartContainerWrapper>
              {llmProxyStatistics.length > 5 && (
                <p className="text-xs text-muted-foreground text-center mt-2">
                  Chart shows top 5 by cost
                </p>
              )}
            </div>

            <StatisticsTablePanel>
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead className="bg-card sticky top-0 z-10">
                      Name
                    </TableHead>
                    <TableHead className="bg-card sticky top-0 z-10">
                      Team
                    </TableHead>
                    <TableHead className="bg-card sticky top-0 z-10">
                      Requests
                    </TableHead>
                    <TableHead className="bg-card sticky top-0 z-10">
                      Tokens
                    </TableHead>
                    <TableHead className="bg-card sticky top-0 z-10 text-right">
                      Cost
                    </TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {sortedLlmProxyStatistics.length === 0 ? (
                    <TableRow>
                      <TableCell
                        colSpan={5}
                        className="text-center py-8 text-muted-foreground"
                      >
                        No LLM proxy data available for the selected timeframe
                      </TableCell>
                    </TableRow>
                  ) : (
                    sortedLlmProxyStatistics.map((proxy) => (
                      <TableRow key={proxy.agentId}>
                        <TableCell className="font-medium">
                          {proxy.agentName}
                        </TableCell>
                        <TableCell>{proxy.teamName}</TableCell>
                        <TableCell>{proxy.requests.toLocaleString()}</TableCell>
                        <TableCell>
                          {(
                            proxy.inputTokens + proxy.outputTokens
                          ).toLocaleString()}
                        </TableCell>
                        <TableCell className="text-right">
                          ${proxy.cost.toFixed(2)}
                        </TableCell>
                      </TableRow>
                    ))
                  )}
                </TableBody>
              </Table>
            </StatisticsTablePanel>
          </div>
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle>Models</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="space-y-4">
            <div className="space-y-3">
              <ChartContainerWrapper
                config={modelChartConfig}
                data={modelChartData}
                emptyMessage="No model data available"
              >
                <LineChart
                  accessibilityLayer
                  data={modelChartData}
                  margin={{ top: 12, left: 12, right: 12 }}
                >
                  <CartesianGrid vertical={false} />
                  <XAxis
                    dataKey="label"
                    tickLine={false}
                    axisLine={false}
                    tickMargin={8}
                  />
                  <YAxis
                    tickLine={false}
                    axisLine={false}
                    tickMargin={8}
                    tickFormatter={(value) => `$${value}`}
                  />
                  <ChartTooltip content={CostChartTooltip} />
                  <ChartLegend content={<ChartLegendContent />} />
                  {modelStatistics.slice(0, 5).map((model) => (
                    <Line
                      key={model.model}
                      dataKey={model.model}
                      type="monotone"
                      stroke={`var(--color-${model.model})`}
                      strokeWidth={2}
                      dot={{
                        strokeWidth: 0,
                        r: 3,
                        fill: `var(--color-${model.model})`,
                      }}
                      activeDot={{ strokeWidth: 0, r: 5 }}
                    />
                  ))}
                </LineChart>
              </ChartContainerWrapper>
              {modelStatistics.length > 5 && (
                <p className="text-xs text-muted-foreground text-center mt-2">
                  Chart shows top 5 by cost
                </p>
              )}
            </div>

            <StatisticsTablePanel>
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead className="bg-card sticky top-0 z-10">
                      Model
                    </TableHead>
                    <TableHead className="bg-card sticky top-0 z-10">
                      Requests
                    </TableHead>
                    <TableHead className="bg-card sticky top-0 z-10">
                      Tokens Used
                    </TableHead>
                    <TableHead className="bg-card sticky top-0 z-10">
                      Cost
                    </TableHead>
                    <TableHead className="bg-card sticky top-0 z-10 text-right">
                      % of Total
                    </TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {sortedModelStatistics.length === 0 ? (
                    <TableRow>
                      <TableCell
                        colSpan={5}
                        className="text-center py-8 text-muted-foreground"
                      >
                        No model data available for the selected timeframe
                      </TableCell>
                    </TableRow>
                  ) : (
                    sortedModelStatistics.map((model) => (
                      <TableRow key={model.model}>
                        <TableCell className="font-medium">
                          {model.model}
                        </TableCell>
                        <TableCell>{model.requests.toLocaleString()}</TableCell>
                        <TableCell>
                          {(
                            model.inputTokens + model.outputTokens
                          ).toLocaleString()}
                        </TableCell>
                        <TableCell>${model.cost.toFixed(2)}</TableCell>
                        <TableCell className="text-right">
                          {model.percentage.toFixed(1)}%
                        </TableCell>
                      </TableRow>
                    ))
                  )}
                </TableBody>
              </Table>
            </StatisticsTablePanel>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}

function StatisticsTablePanel({ children }: { children: React.ReactNode }) {
  return (
    <div
      className={`${STATISTICS_TABLE_MAX_HEIGHT_CLASS} overflow-auto rounded-md border`}
    >
      {children}
    </div>
  );
}

function parseCustomTimeframe(timeframe: StatisticsTimeFrame):
  | {
      from: Date;
      to: Date;
    }
  | undefined {
  if (!timeframe.startsWith("custom:")) {
    return undefined;
  }

  const [from, to] = timeframe.replace("custom:", "").split("_");
  if (!from || !to) {
    return undefined;
  }

  const fromDate = new Date(from);
  const toDate = new Date(to);
  if (Number.isNaN(fromDate.getTime()) || Number.isNaN(toDate.getTime())) {
    return undefined;
  }

  return { from: fromDate, to: toDate };
}
