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";

// Rounds `end` UP to the start of the NEXT minute so:
//   • all data from the current minute is included (no recent entries cut off)
//   • the key string is identical for every render within the same 60-second window
//     → React Query reuses the cached result, no per-render HTTP floods
function buildDateRange(range: Range) {
  const days = range === "7d" ? 7 : 30;
  const now = new Date();
  // setSeconds(60, 0) rolls the clock forward to the next whole minute in JS.
  // e.g. 18:48:34.713 → 18:49:00.000
  now.setSeconds(60, 0);
  const end = now;
  const start = subDays(end, days);
  return { start: start.toISOString(), end: end.toISOString() };
}

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

  const { start, end } = buildDateRange(range);

  const { data, isLoading, isError } = useAuditLogs(
    { start, end, limit: 1000 },
    60_000  // 60s — halves request frequency vs previous 30s
  );

  const chartData = useMemo(() => {
    // Pre-fill all days in range with zeros regardless of API result.
    const map = new Map<string, { requests: number; errors: number }>();
    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 });
    }

    if (data?.data) {
      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]);

  const hasActivity = chartData.some((d) => d.Requêtes > 0 || d.Erreurs > 0);

  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" />
        ) : isError ? (
          <div className="h-64 flex items-center justify-center text-sm text-muted-foreground">
            Impossible de charger les données.
          </div>
        ) : !hasActivity ? (
          <div className="h-64 flex flex-col items-center justify-center gap-2 text-muted-foreground">
            <p className="text-sm">Aucune requête sur les {days} derniers jours.</p>
            <p className="text-xs">Les données apparaîtront après le premier appel via le proxy.</p>
          </div>
        ) : (
          <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 }} allowDecimals={false} className="text-muted-foreground" />
              <Tooltip />
              <Legend />
              <Line
                type="monotone"
                dataKey="Requêtes"
                stroke="#1e3a5f"
                strokeWidth={2}
                dot={false}
                activeDot={{ r: 4 }}
              />
              <Line
                type="monotone"
                dataKey="Erreurs"
                stroke="#ef4444"
                strokeWidth={2}
                dot={false}
                activeDot={{ r: 4 }}
              />
            </LineChart>
          </ResponsiveContainer>
        )}
      </CardContent>
    </Card>
  );
}
