"use client";

import { useState } from "react";
import { BarChart3, RefreshCw, Loader2, AlertCircle, Info } from "lucide-react";
import { Button } from "@/components/ui/button";
import { StatsOverview } from "../StatsOverview";
import { RevenueOverview } from "../RevenueOverview";
import { TopUsersTable } from "../TopUsersTable";
import { ProviderBreakdownChart } from "../ProviderBreakdownChart";
import { FormatBreakdownChart } from "../FormatBreakdownChart";
import { DateRangeFilter } from "../DateRangeFilter";
import { useTranslationStats } from "../useTranslationStats";
import type { StatsPeriod } from "../types";
import {
  TooltipProvider,
  Tooltip,
  TooltipContent,
  TooltipTrigger,
} from "@/components/ui/tooltip";

const ERROR_RATE_WARNING_THRESHOLD = 5;

export default function StatsPage() {
  const [period, setPeriod] = useState<StatsPeriod>("today");
  const { data, isLoading, error, refetch, isMockData } = useTranslationStats(period);

  return (
    <TooltipProvider>
      <div className="space-y-6">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-3">
            <div className="flex size-10 items-center justify-center rounded-lg bg-blue-500/10">
              <BarChart3 className="size-5 text-blue-500" />
            </div>
            <div>
              <h1 className="text-xl font-semibold text-foreground">
                Statistiques
              </h1>
              <p className="text-sm text-muted-foreground">
                Revenus, MRR, traductions et patterns d&apos;utilisation
              </p>
            </div>
          </div>

          <div className="flex items-center gap-3">
            <DateRangeFilter value={period} onChange={setPeriod} />
            <Tooltip>
              <TooltipTrigger asChild>
                <Button
                  variant="outline"
                  size="sm"
                  className="gap-1.5"
                  onClick={() => refetch()}
                  disabled={isLoading}
                >
                  {isLoading ? (
                    <Loader2 className="size-3.5 animate-spin" />
                  ) : (
                    <RefreshCw className="size-3.5" />
                  )}
                  Actualiser
                </Button>
              </TooltipTrigger>
              <TooltipContent>
                <p>Actualiser les statistiques</p>
              </TooltipContent>
            </Tooltip>
          </div>
        </div>

        {error && (
          <div className="flex items-center gap-2 rounded-lg border border-red-200/30 bg-red-500/10 px-4 py-3 text-red-500">
            <AlertCircle className="size-4" />
            <span className="text-sm">{error}</span>
          </div>
        )}

        <RevenueOverview />

        <StatsOverview data={data} isLoading={isLoading} />

        <div className="grid gap-6 md:grid-cols-2">
          <ProviderBreakdownChart data={data} isLoading={isLoading} />
          <FormatBreakdownChart data={data} isLoading={isLoading} />
        </div>

        <TopUsersTable
          topUsers={data?.top_users ?? []}
          isLoading={isLoading}
        />

        {data && (
          <div className="rounded-lg border border-border bg-card px-4 py-3">
            <span className="text-[10px] font-medium uppercase tracking-wider text-muted-foreground">
              Informations
            </span>
            <div className="mt-2 flex flex-wrap gap-4 text-xs text-muted-foreground">
              {isMockData && (
                <span className="flex items-center gap-1 text-amber-500">
                  <Info className="h-3 w-3" />
                  <strong>Mode Démo</strong> - Données simulées
                </span>
              )}
              <span>
                Rafraîchissement auto:{" "}
                <strong className="text-foreground">toutes les 30 secondes</strong>
              </span>
              <span>
                Période:{" "}
                <strong className="text-foreground">
                  {period === "today"
                    ? "Aujourd'hui"
                    : period === "week"
                    ? "7 derniers jours"
                    : "30 derniers jours"}
                </strong>
              </span>
              {data.error_rate > ERROR_RATE_WARNING_THRESHOLD && (
                <span className="text-orange-500">
                  Taux d&apos;erreur élevé détecté ({data.error_rate.toFixed(1)}%)
                </span>
              )}
            </div>
          </div>
        )}
      </div>
    </TooltipProvider>
  );
}
