import { useState } from "react";
import { format } from "date-fns";
import { fr } from "date-fns/locale";
import { ChevronDown, ChevronRight, ChevronLeft, ChevronRight as ChevronRightPag } from "lucide-react";
import { useAuditLogs } from "@/api/logs";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Skeleton } from "@/components/ui/skeleton";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import type { AuditEntry } from "@/types/api";

const PAGE_SIZE = 50;

const sensitivityVariant: Record<string, "default" | "secondary" | "outline" | "warning" | "destructive"> = {
  none: "outline",
  low: "secondary",
  medium: "warning",
  high: "destructive",
  critical: "destructive",
};

function ExpandedRow({ entry }: { entry: AuditEntry }) {
  return (
    <TableRow className="bg-muted/30 hover:bg-muted/30">
      <TableCell colSpan={7} className="p-4">
        <div className="grid grid-cols-2 md:grid-cols-4 gap-x-6 gap-y-2 text-xs">
          <div>
            <span className="text-muted-foreground">Request ID</span>
            <p className="font-mono">{entry.request_id}</p>
          </div>
          <div>
            <span className="text-muted-foreground">Département</span>
            <p>{entry.department || "—"}</p>
          </div>
          <div>
            <span className="text-muted-foreground">Rôle</span>
            <p className="capitalize">{entry.user_role || "—"}</p>
          </div>
          <div>
            <span className="text-muted-foreground">Latence</span>
            <p>{entry.latency_ms ? `${entry.latency_ms} ms` : "—"}</p>
          </div>
          <div>
            <span className="text-muted-foreground">Tokens entrée / sortie</span>
            <p>{entry.token_input.toLocaleString()} / {entry.token_output.toLocaleString()}</p>
          </div>
          <div>
            <span className="text-muted-foreground">Modèle demandé</span>
            <p className="font-mono">{entry.model_requested}</p>
          </div>
          <div>
            <span className="text-muted-foreground">PII détectées</span>
            <p>{entry.pii_entity_count}</p>
          </div>
          <div>
            <span className="text-muted-foreground">Streaming</span>
            <p>{entry.stream ? "Oui" : "Non"}</p>
          </div>
          {entry.prompt_hash && (
            <div className="col-span-2">
              <span className="text-muted-foreground">Hash prompt</span>
              <p className="font-mono truncate">{entry.prompt_hash}</p>
            </div>
          )}
          {entry.response_hash && (
            <div className="col-span-2">
              <span className="text-muted-foreground">Hash réponse</span>
              <p className="font-mono truncate">{entry.response_hash}</p>
            </div>
          )}
          {entry.error_type && (
            <div>
              <span className="text-muted-foreground">Type d'erreur</span>
              <p className="text-destructive">{entry.error_type}</p>
            </div>
          )}
        </div>
      </TableCell>
    </TableRow>
  );
}

export function LogsPage() {
  const [page, setPage] = useState(0);
  const [provider, setProvider] = useState("");
  const [sensitivity, setSensitivity] = useState("");
  const [userFilter, setUserFilter] = useState("");
  const [expandedRows, setExpandedRows] = useState<Set<string>>(new Set());

  const { data, isLoading } = useAuditLogs(
    {
      provider: provider || undefined,
      min_sensitivity: sensitivity || undefined,
      limit: PAGE_SIZE,
      offset: page * PAGE_SIZE,
    },
    30_000
  );

  const totalPages = data ? Math.ceil(data.total / PAGE_SIZE) : 0;

  const toggleRow = (id: string) => {
    setExpandedRows((prev) => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id);
      else next.add(id);
      return next;
    });
  };

  const resetFilters = () => {
    setProvider("");
    setSensitivity("");
    setUserFilter("");
    setPage(0);
  };

  const filteredData = userFilter.trim()
    ? (data?.data ?? []).filter((e) =>
        e.user_id.toLowerCase().includes(userFilter.toLowerCase())
      )
    : (data?.data ?? []);

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-xl font-bold">Journaux d&apos;audit</h2>
          <p className="text-sm text-muted-foreground">
            Historique immuable de toutes les requêtes IA
          </p>
        </div>
      </div>

      {/* Filters */}
      <div className="flex flex-wrap gap-3 items-center">
        <Select value={provider} onValueChange={(v) => { setProvider(v === "all" ? "" : v); setPage(0); }}>
          <SelectTrigger className="w-40">
            <SelectValue placeholder="Fournisseur" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">Tous</SelectItem>
            <SelectItem value="openai">OpenAI</SelectItem>
            <SelectItem value="anthropic">Anthropic</SelectItem>
            <SelectItem value="azure">Azure</SelectItem>
            <SelectItem value="mistral">Mistral</SelectItem>
            <SelectItem value="ollama">Ollama</SelectItem>
          </SelectContent>
        </Select>

        <Select value={sensitivity} onValueChange={(v) => { setSensitivity(v === "all" ? "" : v); setPage(0); }}>
          <SelectTrigger className="w-44">
            <SelectValue placeholder="Sensibilité min." />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">Toutes</SelectItem>
            <SelectItem value="low">Faible</SelectItem>
            <SelectItem value="medium">Moyenne</SelectItem>
            <SelectItem value="high">Haute</SelectItem>
            <SelectItem value="critical">Critique</SelectItem>
          </SelectContent>
        </Select>

        <Input
          placeholder="Filtrer par utilisateur…"
          value={userFilter}
          onChange={(e) => setUserFilter(e.target.value)}
          className="w-52"
        />

        {(provider || sensitivity || userFilter) && (
          <Button variant="ghost" size="sm" onClick={resetFilters}>
            Réinitialiser
          </Button>
        )}
      </div>

      {isLoading ? (
        <div className="space-y-2">
          {Array.from({ length: 8 }).map((_, i) => (
            <Skeleton key={i} className="h-12 w-full" />
          ))}
        </div>
      ) : !data || filteredData.length === 0 ? (
        <div className="flex items-center justify-center h-48 border rounded-lg">
          <p className="text-muted-foreground text-sm">Aucun journal trouvé</p>
        </div>
      ) : (
        <>
          <div className="rounded-lg border">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead className="w-8" />
                  <TableHead>Horodatage</TableHead>
                  <TableHead>Utilisateur</TableHead>
                  <TableHead>Fournisseur / Modèle</TableHead>
                  <TableHead>Tokens</TableHead>
                  <TableHead>Coût</TableHead>
                  <TableHead>Sensibilité</TableHead>
                  <TableHead>Statut</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {filteredData.map((entry) => {
                  const isExpanded = expandedRows.has(entry.request_id);
                  return (
                    <>
                      <TableRow
                        key={entry.request_id}
                        className="cursor-pointer"
                        onClick={() => toggleRow(entry.request_id)}
                      >
                        <TableCell className="pr-0">
                          {isExpanded
                            ? <ChevronDown className="h-3 w-3 text-muted-foreground" />
                            : <ChevronRight className="h-3 w-3 text-muted-foreground" />}
                        </TableCell>
                        <TableCell className="text-xs text-muted-foreground whitespace-nowrap">
                          {format(new Date(entry.timestamp), "dd/MM/yy HH:mm:ss", { locale: fr })}
                        </TableCell>
                        <TableCell className="text-sm">{entry.user_id}</TableCell>
                        <TableCell>
                          <span className="text-xs font-mono">
                            {entry.provider}/{entry.model_used}
                          </span>
                        </TableCell>
                        <TableCell className="text-sm">{entry.token_total.toLocaleString()}</TableCell>
                        <TableCell className="text-sm">${entry.cost_usd.toFixed(5)}</TableCell>
                        <TableCell>
                          <Badge variant={sensitivityVariant[entry.sensitivity_level] ?? "outline"}>
                            {entry.sensitivity_level || "—"}
                          </Badge>
                        </TableCell>
                        <TableCell>
                          <Badge variant={entry.status === "ok" ? "success" : "destructive"}>
                            {entry.status}
                          </Badge>
                        </TableCell>
                      </TableRow>
                      {isExpanded && <ExpandedRow key={`exp-${entry.request_id}`} entry={entry} />}
                    </>
                  );
                })}
              </TableBody>
            </Table>
          </div>

          {/* Pagination */}
          <div className="flex items-center justify-between text-sm text-muted-foreground">
            <span>
              {data.total} résultat{data.total !== 1 ? "s" : ""} · {PAGE_SIZE} par page
            </span>
            <div className="flex items-center gap-2">
              <Button
                variant="outline"
                size="icon"
                onClick={() => setPage((p) => Math.max(0, p - 1))}
                disabled={page === 0}
              >
                <ChevronLeft className="h-4 w-4" />
              </Button>
              <span>
                Page {page + 1} / {totalPages || 1}
              </span>
              <Button
                variant="outline"
                size="icon"
                onClick={() => setPage((p) => Math.min(totalPages - 1, p + 1))}
                disabled={page >= totalPages - 1}
              >
                <ChevronRightPag className="h-4 w-4" />
              </Button>
            </div>
          </div>
        </>
      )}
    </div>
  );
}
