import { Activity, DollarSign, AlertTriangle, Zap } from "lucide-react";
import { KpiCard } from "@/components/KpiCard";
import { VolumeChart } from "@/components/VolumeChart";
import { useRequestCount } from "@/api/logs";
import { useCosts } from "@/api/costs";
import { format } from "date-fns";
import { fr } from "date-fns/locale";

export function OverviewPage() {
  const { data: requestCount, isLoading: logsLoading, dataUpdatedAt } = useRequestCount();
  const { data: costData, isLoading: costsLoading } = useCosts({}, 30_000);

  const totalCost = costData?.data.reduce((sum, c) => sum + c.total_cost_usd, 0) ?? 0;
  const totalTokens = costData?.data.reduce((sum, c) => sum + c.total_tokens, 0) ?? 0;
  const requestCountByProvider = costData?.data.length ?? 0;

  const lastUpdated = dataUpdatedAt
    ? format(new Date(dataUpdatedAt), "HH:mm:ss", { locale: fr })
    : null;

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-xl font-bold">Vue d&apos;ensemble</h2>
          <p className="text-sm text-muted-foreground">
            Activité IA de votre organisation
            {lastUpdated && ` · Mis à jour à ${lastUpdated} (auto-refresh 30s)`}
          </p>
        </div>
      </div>

      {/* KPI Cards */}
      <div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-4 gap-4">
        <KpiCard
          title="Requêtes totales"
          value={requestCount?.toLocaleString("fr-FR")}
          subtitle="Toutes périodes confondues"
          icon={Activity}
          isLoading={logsLoading}
        />
        <KpiCard
          title="Coût total (USD)"
          value={`$${totalCost.toFixed(4)}`}
          subtitle="Toutes périodes confondues"
          icon={DollarSign}
          isLoading={costsLoading}
        />
        <KpiCard
          title="Tokens consommés"
          value={totalTokens.toLocaleString("fr-FR")}
          subtitle="Total de la période"
          icon={Zap}
          isLoading={costsLoading}
        />
        <KpiCard
          title="Fournisseurs actifs"
          value={requestCountByProvider}
          subtitle="Avec des requêtes enregistrées"
          icon={AlertTriangle}
          isLoading={costsLoading}
        />
      </div>

      {/* Volume Chart */}
      <VolumeChart />

      {/* Cost by provider */}
      {costData && costData.data.length > 0 && (
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div className="rounded-lg border bg-card p-4">
            <h3 className="text-sm font-semibold mb-3">Coûts par fournisseur</h3>
            <div className="space-y-2">
              {costData.data.map((c) => (
                <div key={c.key} className="flex items-center justify-between text-sm">
                  <span className="text-muted-foreground capitalize">{c.key}</span>
                  <div className="flex gap-4">
                    <span className="text-muted-foreground">
                      {c.request_count.toLocaleString("fr-FR")} req
                    </span>
                    <span className="font-medium">${c.total_cost_usd.toFixed(4)}</span>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
