import DashboardLayout from "@/components/DashboardLayout";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { Badge } from "@/components/ui/badge";
import { trpc } from "@/lib/trpc";
import { History as HistoryIcon, FileText, Trash2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { toast } from "sonner";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from "@/components/ui/alert-dialog";

export default function History() {
  const { data: logs, isLoading } = trpc.importLogs.getByUser.useQuery();
  const deleteAllMutation = trpc.importLogs.deleteAll.useMutation();
  const utils = trpc.useUtils();
  
  const handleDeleteAll = async () => {
    try {
      await deleteAllMutation.mutateAsync();
      await utils.importLogs.getByUser.invalidate();
      toast.success("Logs supprimés", {
        description: "Tous les logs d'import ont été supprimés avec succès.",
      });
    } catch (error) {
      toast.error("Erreur", {
        description: "Impossible de supprimer les logs d'import.",
      });
    }
  };

  return (
    <DashboardLayout>
      <div className="space-y-6">
        <div className="flex justify-between items-start">
          <div>
            <h1 className="text-3xl font-bold">Historique des imports</h1>
            <p className="text-gray-500 mt-1">Consultez l'historique de tous vos imports de factures</p>
          </div>
          
          {logs && logs.length > 0 && (
            <AlertDialog>
              <AlertDialogTrigger asChild>
                <Button variant="destructive" size="sm">
                  <Trash2 className="mr-2 h-4 w-4" />
                  Effacer les logs
                </Button>
              </AlertDialogTrigger>
              <AlertDialogContent>
                <AlertDialogHeader>
                  <AlertDialogTitle>Êtes-vous sûr ?</AlertDialogTitle>
                  <AlertDialogDescription>
                    Cette action supprimera définitivement tous les logs d'import. Cette opération est irréversible.
                  </AlertDialogDescription>
                </AlertDialogHeader>
                <AlertDialogFooter>
                  <AlertDialogCancel>Annuler</AlertDialogCancel>
                  <AlertDialogAction
                    onClick={handleDeleteAll}
                    disabled={deleteAllMutation.isPending}
                    className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
                  >
                    {deleteAllMutation.isPending ? "Suppression..." : "Supprimer"}
                  </AlertDialogAction>
                </AlertDialogFooter>
              </AlertDialogContent>
            </AlertDialog>
          )}
        </div>

        <Card>
          <CardHeader>
            <CardTitle>Logs d'import</CardTitle>
            <CardDescription>Détails de chaque import avec statistiques</CardDescription>
          </CardHeader>
          <CardContent>
            {isLoading ? (
              <div className="text-center py-8 text-gray-500">Chargement...</div>
            ) : logs && logs.length > 0 ? (
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Fichier</TableHead>
                    <TableHead>Date</TableHead>
                    <TableHead>Détectées</TableHead>
                    <TableHead>Importées</TableHead>
                    <TableHead>Doublons</TableHead>
                    <TableHead>Erreurs</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {logs.map((log) => (
                    <TableRow key={log.id}>
                      <TableCell className="font-medium">{log.fileName}</TableCell>
                      <TableCell>
                        {new Date(log.importedAt).toLocaleString("fr-FR")}
                      </TableCell>
                      <TableCell>
                        <Badge variant="outline">{log.totalInvoicesDetected}</Badge>
                      </TableCell>
                      <TableCell>
                        <Badge className="bg-green-100 text-green-800 hover:bg-green-100">
                          {log.invoicesImported}
                        </Badge>
                      </TableCell>
                      <TableCell>
                        {log.duplicatesIgnored > 0 ? (
                          <Badge className="bg-yellow-100 text-yellow-800 hover:bg-yellow-100">
                            {log.duplicatesIgnored}
                          </Badge>
                        ) : (
                          <span className="text-gray-400">-</span>
                        )}
                      </TableCell>
                      <TableCell>
                        {log.errors > 0 ? (
                          <Badge className="bg-red-100 text-red-800 hover:bg-red-100">
                            {log.errors}
                          </Badge>
                        ) : (
                          <span className="text-gray-400">-</span>
                        )}
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            ) : (
              <div className="text-center py-8 text-gray-500">
                <HistoryIcon className="w-12 h-12 mx-auto mb-3 text-gray-300" />
                <p>Aucun historique d'import</p>
              </div>
            )}
          </CardContent>
        </Card>
      </div>
    </DashboardLayout>
  );
}
