import { useState, useMemo } from "react";
import {
  LineChart,
  Line,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
  Legend,
} from "recharts";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Skeleton } from "@/components/ui/skeleton";
import { useAuditLogs } from "@/api/logs";
import { format, subDays, parseISO, startOfDay } from "date-fns";
import { fr } from "date-fns/locale";

type Range = "7d" | "30d";

function buildDateRange(range: Range) {
  const days = range === "7d" ? 7 : 30;
  const end = new Date();
  const start = subDays(end, days);
  return { start: start.toISOString(), end: end.toISOString() };
}

export function VolumeChart() {
  const [range, setRange] = useState<Range>("7d");
  const { start, end } = buildDateRange(range);
  const days = range === "7d" ? 7 : 30;

  const { data, isLoading } = useAuditLogs(
    { start, end, limit: 1000 },
    30_000
  );

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

    // Group by day
    const map = new Map<string, { requests: number; errors: number }>();

    // Pre-fill all days in range
    for (let i = days - 1; i >= 0; i--) {
      const d = format(subDays(new Date(), i), "yyyy-MM-dd");
      map.set(d, { requests: 0, errors: 0 });
    }

    for (const entry of data.data) {
      const day = format(startOfDay(parseISO(entry.timestamp)), "yyyy-MM-dd");
      const existing = map.get(day) ?? { requests: 0, errors: 0 };
      existing.requests++;
      if (entry.status === "error") existing.errors++;
      map.set(day, existing);
    }

    return Array.from(map.entries()).map(([date, stats]) => ({
      date: format(parseISO(date), "dd/MM", { locale: fr }),
      Requêtes: stats.requests,
      Erreurs: stats.errors,
    }));
  }, [data, days]);

  return (
    <Card>
      <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
        <CardTitle className="text-base font-semibold">Volume des requêtes</CardTitle>
        <div className="flex gap-1">
          <Button
            variant={range === "7d" ? "default" : "outline"}
            size="sm"
            onClick={() => setRange("7d")}
          >
            7j
          </Button>
          <Button
            variant={range === "30d" ? "default" : "outline"}
            size="sm"
            onClick={() => setRange("30d")}
          >
            30j
          </Button>
        </div>
      </CardHeader>
      <CardContent>
        {isLoading ? (
          <Skeleton className="h-64 w-full" />
        ) : (
          <ResponsiveContainer width="100%" height={256}>
            <LineChart data={chartData} margin={{ top: 4, right: 16, left: 0, bottom: 0 }}>
              <CartesianGrid strokeDasharray="3 3" className="stroke-border" />
              <XAxis
                dataKey="date"
                tick={{ fontSize: 12 }}
                className="text-muted-foreground"
              />
              <YAxis tick={{ fontSize: 12 }} className="text-muted-foreground" />
              <Tooltip />
              <Legend />
              <Line
                type="monotone"
                dataKey="Requêtes"
                stroke="hsl(222.2 47.4% 11.2%)"
                strokeWidth={2}
                dot={false}
              />
              <Line
                type="monotone"
                dataKey="Erreurs"
                stroke="hsl(0 84.2% 60.2%)"
                strokeWidth={2}
                dot={false}
              />
            </LineChart>
          </ResponsiveContainer>
        )}
      </CardContent>
    </Card>
  );
}
