import { useState } from "react";
import DashboardLayout from "@/components/DashboardLayout";
import { useAuth } from "@/_core/hooks/useAuth";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { Checkbox } from "@/components/ui/checkbox";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { trpc } from "@/lib/trpc";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Search, FileText, Download, FileSpreadsheet, Trash2, Edit, Trash, Filter, LayoutList, LayoutGrid, ArrowUpDown, ArrowUp, ArrowDown } from "lucide-react";
import * as XLSX from 'xlsx';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
import { toast } from "sonner";
import { useLocation } from "wouter";

type SortField = "invoiceDate" | "createdAt";
type SortDir = "asc" | "desc";

export default function Invoices() {
  const [, setLocation] = useLocation();
  const [searchQuery, setSearchQuery] = useState("");
  const [compactMode, setCompactMode] = useState(true);
  const [sortField, setSortField] = useState<SortField>("createdAt");
  const [sortDir, setSortDir] = useState<SortDir>("desc");
  const [selectedIds, setSelectedIds] = useState<number[]>([]);
  const [statusFilter, setStatusFilter] = useState<string>("all");
  const [recipientFilter, setRecipientFilter] = useState<string>("all");
  const [subscriptionFilter, setSubscriptionFilter] = useState<string>("all"); // all | yes | no
  const [entityFilter, setEntityFilter] = useState<string>("all"); // all | santinova | itinova
  const [ventilationFilter, setVentilationFilter] = useState<string>("all");
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [invoiceToDelete, setInvoiceToDelete] = useState<number | null>(null);
  const [addDialogOpen, setAddDialogOpen] = useState(false);
  const [addDialogType, setAddDialogType] = useState<"service" | "ventilation" | null>(null);
  const [newItemName, setNewItemName] = useState("");
  const [pendingInvoiceId, setPendingInvoiceId] = useState<number | null>(null);
  const [textDialogOpen, setTextDialogOpen] = useState(false);
  const [selectedInvoiceText, setSelectedInvoiceText] = useState<string | null>(null);
  const { user } = useAuth();
  const isAdmin = user?.role === 'admin';
  const { data: invoices, isLoading } = trpc.invoices.list.useQuery();
  const { data: departments } = trpc.departments.getByUser.useQuery();
  const { data: allocations } = trpc.accountingAllocations.getByUser.useQuery();
  const { data: allUsers } = trpc.admin.getAllUsers.useQuery(undefined, { enabled: isAdmin });
  const utils = trpc.useUtils();

  const exportExcelMutation = trpc.sftp.exportToExcel.useMutation({
    onSuccess: (data) => {
      // Generate Excel file
      const worksheet = XLSX.utils.json_to_sheet(data.invoices.map(inv => ({
        'Fournisseur': inv.supplierName,
        'Destinataire': (inv as any).recipientName,
        'N° Facture': inv.invoiceNumber,
        'Date': inv.invoiceDate,
        'N° Bon de livraison': inv.deliveryNoteNumber,
        'N° Commande': inv.orderNumber,
        'Montant': inv.totalAmount,
        'Score': inv.qualityScore,
        'Statut export': inv.exportStatus,
        'Exporté le': inv.exportedAt,
        'Créé le': inv.createdAt,
      })));
      
      const workbook = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(workbook, worksheet, 'Factures');
      
      // Download Excel file
      XLSX.writeFile(workbook, `factures_${new Date().toISOString().split('T')[0]}.xlsx`);
      
      toast.success(`${data.invoices.length} facture(s) export\u00e9e(s) en Excel`);
      setSelectedIds([]);
    },
    onError: (error) => {
      toast.error(error.message || "Erreur lors de l'export Excel");
    },
  });
  
  const exportMutation = trpc.sftp.exportToPdf.useMutation({
    onSuccess: (data) => {
      toast.success(
        `${data.copiedCount} facture(s) exportée(s) avec succès vers:\n${data.exportFolder}`,
        { duration: 5000 }
      );
      
      setSelectedIds([]);
      utils.invoices.list.invalidate();
    },
    onError: (error) => {
      toast.error(error.message || "Erreur lors de l'export");
    },
  });

  const deleteMutation = trpc.invoices.delete.useMutation({
    onSuccess: () => {
      toast.success("Facture supprimée avec succès");
      utils.invoices.list.invalidate();
      setDeleteDialogOpen(false);
      setInvoiceToDelete(null);
    },
    onError: (error) => {
      toast.error(error.message || "Erreur lors de la suppression");
    },
  });

  const upsertLearningMutation = trpc.learnings.upsert.useMutation();

  const updateFieldMutation = trpc.invoices.update.useMutation({
    onSuccess: () => {
      toast.success("Facture mise à jour");
      utils.invoices.list.invalidate();
    },
    onError: (error) => {
      toast.error(error.message || "Erreur lors de la mise à jour");
    },
  });

  const createDepartmentMutation = trpc.departments.create.useMutation({
    onSuccess: (newDept) => {
      toast.success("Service ajouté avec succès");
      utils.departments.getByUser.invalidate();
      // Update the invoice with the new department
      if (pendingInvoiceId) {
        updateFieldMutation.mutate({
          id: pendingInvoiceId,
          data: { serviceConcerne: newDept.name },
        });
      }
      setAddDialogOpen(false);
      setNewItemName("");
      setPendingInvoiceId(null);
    },
    onError: (error) => {
      toast.error(error.message || "Erreur lors de l'ajout");
    },
  });

  const createAllocationMutation = trpc.accountingAllocations.create.useMutation({
    onSuccess: (newAlloc) => {
      toast.success("Ventilation ajoutée avec succès");
      utils.accountingAllocations.getByUser.invalidate();
      // Update the invoice with the new allocation
      if (pendingInvoiceId) {
        updateFieldMutation.mutate({
          id: pendingInvoiceId,
          data: { ventilationComptable: newAlloc.name },
        });
      }
      setAddDialogOpen(false);
      setNewItemName("");
      setPendingInvoiceId(null);
    },
    onError: (error) => {
      toast.error(error.message || "Erreur lors de l'ajout");
    },
  });

  const handleAddNewItem = () => {
    if (!newItemName.trim()) {
      toast.error("Le nom ne peut pas être vide");
      return;
    }
    if (addDialogType === "service") {
      createDepartmentMutation.mutate({ name: newItemName.trim() });
    } else if (addDialogType === "ventilation") {
      createAllocationMutation.mutate({ name: newItemName.trim() });
    }
  };

  // Collect unique recipients for the filter dropdown
  const uniqueRecipients = Array.from(
    new Set(
      (invoices || []).map(inv => (inv as any).recipientName).filter(Boolean)
    )
  ).sort();

  const uniqueVentilations = Array.from(
    new Set(
      (invoices || []).map(inv => (inv as any).ventilationComptable).filter(Boolean)
    )
  ).sort();

  const handleSort = (field: SortField) => {
    if (sortField === field) {
      setSortDir(d => d === "asc" ? "desc" : "asc");
    } else {
      setSortField(field);
      setSortDir("desc");
    }
  };

  const SortIcon = ({ field }: { field: SortField }) => {
    if (sortField !== field) return <ArrowUpDown className="w-3 h-3 ml-1 opacity-40" />;
    return sortDir === "asc" ? <ArrowUp className="w-3 h-3 ml-1" /> : <ArrowDown className="w-3 h-3 ml-1" />;
  };

  const filteredInvoices = invoices?.filter((inv) => {
    // Filter by search query
    if (searchQuery) {
      const query = searchQuery.toLowerCase();
      const matchesSearch = inv.supplierName?.toLowerCase().includes(query) ||
        inv.invoiceNumber?.toLowerCase().includes(query) ||
        (inv as any).recipientName?.toLowerCase().includes(query);
      if (!matchesSearch) return false;
    }
    
    // Filter by export status
    if (statusFilter !== "all") {
      if (statusFilter === "exported" && inv.exportStatus !== "exported") return false;
      if (statusFilter === "not_exported" && inv.exportStatus !== "not_exported") return false;
      if (statusFilter === "export_error" && inv.exportStatus !== "export_error") return false;
    }

    // Filter by recipient
    if (recipientFilter !== "all") {
      if (recipientFilter === "__empty__") {
        if ((inv as any).recipientName) return false;
      } else {
        if ((inv as any).recipientName !== recipientFilter) return false;
      }
    }
    // Filter by subscription
    if (subscriptionFilter !== "all") {
      const isSub = (inv as any).isSubscription === 1 || (inv as any).isSubscription === true;
      if (subscriptionFilter === "yes" && !isSub) return false;
      if (subscriptionFilter === "no" && isSub) return false;
    }
    // Filter by entity (SANTINOVA = serviceConcerne === 'DSI SANTINOVA', ITINOVA = autre)
    if (entityFilter !== "all") {
      const service = ((inv as any).serviceConcerne || "").trim().toUpperCase();
      if (entityFilter === "santinova" && service !== "DSI SANTINOVA") return false;
      if (entityFilter === "itinova" && service === "DSI SANTINOVA") return false;
    }
    // Filter by ventilation comptable
    if (ventilationFilter !== "all") {
      if (ventilationFilter === "__empty__") {
        if ((inv as any).ventilationComptable) return false;
      } else {
        if ((inv as any).ventilationComptable !== ventilationFilter) return false;
      }
    }
    return true;
  });
  
  const statusCounts = {
    all: invoices?.length || 0,
    exported: invoices?.filter(inv => inv.exportStatus === "exported").length || 0,
    not_exported: invoices?.filter(inv => inv.exportStatus === "not_exported").length || 0,
    export_error: invoices?.filter(inv => inv.exportStatus === "export_error").length || 0,
  };
  
  // Old filter logic (to be removed)
  const _oldFilteredInvoices = invoices?.filter((inv) => {
    if (!searchQuery) return true;
    const query = searchQuery.toLowerCase();
    return (
      inv.supplierName?.toLowerCase().includes(query) ||
      inv.invoiceNumber?.toLowerCase().includes(query)
    );
  });

  const handleSelectAll = (checked: boolean) => {
    if (checked) {
      // Select all invoices (no restriction)
      const allIds = (filteredInvoices || []).map(inv => inv.id);
      setSelectedIds(allIds);
    } else {
      setSelectedIds([]);
    }
  };

  const handleSelectOne = (id: number, checked: boolean) => {
    if (checked) {
      setSelectedIds([...selectedIds, id]);
    } else {
      setSelectedIds(selectedIds.filter(selectedId => selectedId !== id));
    }
  };

  const handleExport = () => {
    if (selectedIds.length === 0) {
      toast.error("Veuillez s\u00e9lectionner au moins une facture");
      return;
    }
    
    exportMutation.mutate({ invoiceIds: selectedIds });
  };
  
  const handleExportExcel = () => {
    if (selectedIds.length === 0) {
      toast.error("Veuillez s\u00e9lectionner au moins une facture");
      return;
    }
    
    exportExcelMutation.mutate({ invoiceIds: selectedIds });
  };

  const getExportStatusBadge = (status: string) => {
    switch (status) {
      case "exported":
        return <Badge className="bg-green-100 text-green-800 hover:bg-green-100">Exporté</Badge>;
      case "not_exported":
        return <Badge className="bg-blue-100 text-blue-800 hover:bg-blue-100">Non exporté</Badge>;
      case "export_error":
        return <Badge className="bg-red-100 text-red-800 hover:bg-red-100">Erreur export</Badge>;
      default:
        return <Badge variant="outline">{status}</Badge>;
    }
  };

  const getQualityBadge = (score: number | null) => {
    if (score === null) return <Badge variant="outline">-</Badge>;
    if (score === 100) return <Badge className="bg-green-100 text-green-800 hover:bg-green-100">{score}%</Badge>;
    if (score >= 80) return <Badge className="bg-yellow-100 text-yellow-800 hover:bg-yellow-100">{score}%</Badge>;
    return <Badge className="bg-red-100 text-red-800 hover:bg-red-100">{score}%</Badge>;
  };

  const isEligibleForExport = (invoice: any) => {
    return (invoice.qualityScore || 0) === 100;
  };
  
  const hasOnlyEligibleSelected = selectedIds.length > 0 && selectedIds.every(id => {
    const invoice = invoices?.find(inv => inv.id === id);
    return invoice && isEligibleForExport(invoice);
  });

  const sortedInvoices = [...(filteredInvoices || [])].sort((a, b) => {
    let aVal: number, bVal: number;
    if (sortField === "invoiceDate") {
      aVal = a.invoiceDate ? new Date(a.invoiceDate).getTime() : 0;
      bVal = b.invoiceDate ? new Date(b.invoiceDate).getTime() : 0;
    } else {
      aVal = a.createdAt ? new Date(a.createdAt as unknown as string).getTime() : 0;
      bVal = b.createdAt ? new Date(b.createdAt as unknown as string).getTime() : 0;
    }
    return sortDir === "asc" ? aVal - bVal : bVal - aVal;
  });

  const allEligibleSelected = (sortedInvoices.length || 0) > 0 && 
    sortedInvoices.filter(inv => isEligibleForExport(inv)).every(inv => selectedIds.includes(inv.id));

  return (
    <DashboardLayout>
      <div className="space-y-6">
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-3xl font-bold">Factures</h1>
            <p className="text-gray-500 mt-1">Gérez toutes vos factures importées</p>
          </div>
          <div className="flex gap-2">
            <Button
              onClick={handleExportExcel}
              disabled={selectedIds.length === 0 || exportExcelMutation.isPending}
              variant="outline"
              className="border-green-600 text-green-600 hover:bg-green-50"
            >
              <FileSpreadsheet className="w-4 h-4 mr-2" />
              Excel ({selectedIds.length})
            </Button>
            <Button
              onClick={handleExport}
              disabled={selectedIds.length === 0 || !hasOnlyEligibleSelected || exportMutation.isPending}
              className="bg-blue-600 hover:bg-blue-700"
              title={!hasOnlyEligibleSelected && selectedIds.length > 0 ? "Seules les factures avec un score de 100% peuvent être exportées" : ""}
            >
              <Download className="w-4 h-4 mr-2" />
              PDF ({selectedIds.length})
            </Button>
            <Button
              onClick={async () => {
                if (confirm(`Voulez-vous vraiment supprimer ${selectedIds.length} facture(s) ?`)) {
                  try {
                    for (const id of selectedIds) {
                      await utils.client.invoices.delete.mutate({ id });
                    }
                    toast.success(`${selectedIds.length} facture(s) supprimée(s)`);
                    setSelectedIds([]);
                    utils.invoices.list.invalidate();
                  } catch (error: any) {
                    toast.error(error.message || "Erreur lors de la suppression");
                  }
                }
              }}
              disabled={selectedIds.length === 0}
              variant="destructive"
            >
              <Trash2 className="w-4 h-4 mr-2" />
              Supprimer ({selectedIds.length})
            </Button>
            <Button onClick={() => setLocation("/upload")}>
              <FileText className="w-4 h-4 mr-2" />
              Importer
            </Button>
          </div>
        </div>

        {/* ===== CARTOUCHE FILTRES ===== */}
        <div className="rounded-xl border border-blue-100 bg-blue-50/60 px-4 py-3 mb-4 shadow-sm">

          {/* Ligne 1 : Recherche + affichage compact/détail */}
          <div className="flex gap-3 items-center flex-wrap mb-3">
            <div className="relative flex-1 min-w-[220px]">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-blue-400 w-4 h-4" />
              <Input
                placeholder="Rechercher par fournisseur, destinataire ou numéro..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="pl-10 bg-white border-blue-200 focus:border-blue-400"
              />
            </div>
            <div className="flex gap-1 shrink-0">
              <Button
                variant={compactMode ? "default" : "outline"}
                size="sm"
                onClick={() => setCompactMode(true)}
                title="Mode compact"
                className={compactMode ? "bg-blue-600 hover:bg-blue-700" : "bg-white border-blue-200 text-blue-700 hover:bg-blue-50"}
              >
                <LayoutList className="w-4 h-4 mr-1" /> Compact
              </Button>
              <Button
                variant={!compactMode ? "default" : "outline"}
                size="sm"
                onClick={() => setCompactMode(false)}
                title="Mode détail"
                className={!compactMode ? "bg-blue-600 hover:bg-blue-700" : "bg-white border-blue-200 text-blue-700 hover:bg-blue-50"}
              >
                <LayoutGrid className="w-4 h-4 mr-1" /> Détail
              </Button>
            </div>
          </div>

          {/* Ligne 2 : Filtres destinataire, abonnement, entité, ventilation */}
          <div className="flex gap-2 items-center flex-wrap mb-3">
            <Filter className="w-4 h-4 text-blue-400 shrink-0" />
            <Select value={recipientFilter} onValueChange={setRecipientFilter}>
              <SelectTrigger className="w-[180px] bg-white border-blue-200 text-sm">
                <SelectValue placeholder="Destinataire" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">Tous destinataires</SelectItem>
                <SelectItem value="__empty__">Sans destinataire</SelectItem>
                {uniqueRecipients.map((r) => (
                  <SelectItem key={r} value={r}>{r}</SelectItem>
                ))}
              </SelectContent>
            </Select>
            <Select value={subscriptionFilter} onValueChange={setSubscriptionFilter}>
              <SelectTrigger className="w-[170px] bg-white border-blue-200 text-sm">
                <SelectValue placeholder="Abonnement" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">Abonnement : tous</SelectItem>
                <SelectItem value="yes">Abonnement : OUI</SelectItem>
                <SelectItem value="no">Abonnement : NON</SelectItem>
              </SelectContent>
            </Select>
            <Select value={entityFilter} onValueChange={setEntityFilter}>
              <SelectTrigger className="w-[150px] bg-white border-blue-200 text-sm">
                <SelectValue placeholder="Entité" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">Toutes entités</SelectItem>
                <SelectItem value="santinova">SANTINOVA</SelectItem>
                <SelectItem value="itinova">ITINOVA</SelectItem>
              </SelectContent>
            </Select>
            <Select value={ventilationFilter} onValueChange={setVentilationFilter}>
              <SelectTrigger className="w-[170px] bg-white border-blue-200 text-sm">
                <SelectValue placeholder="Ventilation" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">Toutes ventilations</SelectItem>
                <SelectItem value="__empty__">Sans ventilation</SelectItem>
                {uniqueVentilations.map((v) => (
                  <SelectItem key={v} value={v}>{v}</SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          {/* Ligne 3 : Boutons statut export + tri */}
          <div className="flex gap-2 items-center flex-wrap">
            <Button
              variant={statusFilter === "all" ? "default" : "outline"}
              onClick={() => setStatusFilter("all")}
              size="sm"
              className={statusFilter === "all" ? "bg-blue-600 hover:bg-blue-700" : "bg-white border-blue-200 text-blue-700 hover:bg-blue-50"}
            >
              Tous ({statusCounts.all})
            </Button>
            <Button
              variant={statusFilter === "exported" ? "default" : "outline"}
              onClick={() => setStatusFilter("exported")}
              size="sm"
              className={statusFilter === "exported" ? "bg-green-600 hover:bg-green-700 text-white" : "bg-white border-green-200 text-green-700 hover:bg-green-50"}
            >
              Exportés ({statusCounts.exported})
            </Button>
            <Button
              variant={statusFilter === "not_exported" ? "default" : "outline"}
              onClick={() => setStatusFilter("not_exported")}
              size="sm"
              className={statusFilter === "not_exported" ? "bg-indigo-600 hover:bg-indigo-700 text-white" : "bg-white border-indigo-200 text-indigo-700 hover:bg-indigo-50"}
            >
              Non exportés ({statusCounts.not_exported})
            </Button>
            <Button
              variant={statusFilter === "export_error" ? "default" : "outline"}
              onClick={() => setStatusFilter("export_error")}
              size="sm"
              className={statusFilter === "export_error" ? "bg-red-600 hover:bg-red-700 text-white" : "bg-white border-red-200 text-red-700 hover:bg-red-50"}
            >
              Erreurs ({statusCounts.export_error})
            </Button>
            <div className="ml-auto flex gap-1 items-center">
              <span className="text-xs text-blue-500 font-medium mr-1">Trier :</span>
              <Button
                variant={sortField === "createdAt" ? "default" : "outline"}
                size="sm"
                onClick={() => handleSort("createdAt")}
                className={sortField === "createdAt" ? "bg-blue-600 hover:bg-blue-700" : "bg-white border-blue-200 text-blue-700 hover:bg-blue-50"}
              >
                Réception <SortIcon field="createdAt" />
              </Button>
              <Button
                variant={sortField === "invoiceDate" ? "default" : "outline"}
                size="sm"
                onClick={() => handleSort("invoiceDate")}
                className={sortField === "invoiceDate" ? "bg-blue-600 hover:bg-blue-700" : "bg-white border-blue-200 text-blue-700 hover:bg-blue-50"}
              >
                Facture <SortIcon field="invoiceDate" />
              </Button>
            </div>
          </div>
        </div>
        {/* ===== FIN CARTOUCHE ===== */}

        <Card>
          <CardContent className="pt-4">

            {/* Table */}
            {isLoading ? (
              <div className="text-center py-8 text-gray-500">Chargement...</div>
            ) : sortedInvoices.length > 0 ? (
              <div className="border rounded-lg overflow-hidden">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead className="w-12">
                        <Checkbox
                          checked={allEligibleSelected}
                          onCheckedChange={handleSelectAll}
                        />
                      </TableHead>
                      <TableHead>Fournisseur</TableHead>
                      {!compactMode && <TableHead>Destinataire</TableHead>}
                      <TableHead>N° Facture</TableHead>
                      <TableHead
                        className="cursor-pointer select-none"
                        onClick={() => handleSort("invoiceDate")}
                      >
                        <span className="flex items-center">Date facture <SortIcon field="invoiceDate" /></span>
                      </TableHead>
                      <TableHead
                        className="cursor-pointer select-none"
                        onClick={() => handleSort("createdAt")}
                      >
                        <span className="flex items-center">Date réception <SortIcon field="createdAt" /></span>
                      </TableHead>
                      <TableHead>Montant</TableHead>
                      {!compactMode && <TableHead>Service</TableHead>}
                      {!compactMode && <TableHead>Abonnement</TableHead>}
                      <TableHead>Score</TableHead>
                      <TableHead>Statut</TableHead>
                      <TableHead className="w-32">Actions</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {sortedInvoices.map((invoice) => {
                      return (
                        <TableRow key={invoice.id}>
                          <TableCell>
                            <Checkbox
                              checked={selectedIds.includes(invoice.id)}
                              onCheckedChange={(checked) => handleSelectOne(invoice.id, checked as boolean)}
                            />
                          </TableCell>
                          <TableCell className="font-medium">
                            <button
                              onClick={() => setLocation(`/invoices/${invoice.id}`)}
                              className="text-blue-600 hover:text-blue-800 hover:underline"
                            >
                              {invoice.supplierName || "Inconnu"}
                            </button>
                          </TableCell>
                          {!compactMode && <TableCell>{(invoice as any).recipientName || "-"}</TableCell>}
                          <TableCell>{invoice.invoiceNumber || "-"}</TableCell>
                          <TableCell>
                            {invoice.invoiceDate
                              ? new Date(invoice.invoiceDate).toLocaleDateString("fr-FR")
                              : "-"}
                          </TableCell>
                          <TableCell className="text-xs text-gray-500">
                            {invoice.createdAt
                              ? new Date(invoice.createdAt as unknown as string).toLocaleDateString("fr-FR")
                              : "-"}
                          </TableCell>
                          <TableCell>
                            {invoice.totalAmount
                              ? `${parseFloat(invoice.totalAmount as string).toFixed(2)} €`
                              : "-"}
                          </TableCell>
                          {!compactMode && <TableCell className="text-sm">
                            <select
                              value={invoice.serviceConcerne || ""}
                              onChange={(e) => {
                                if (e.target.value === "__ADD_NEW__") {
                                  setPendingInvoiceId(invoice.id);
                                  setAddDialogType("service");
                                  setAddDialogOpen(true);
                                  e.target.value = invoice.serviceConcerne || "";
                                } else {
                                  updateFieldMutation.mutate({
                                    id: invoice.id,
                                    data: { serviceConcerne: e.target.value || undefined },
                                  });
                                }
                              }}
                              className="w-full px-2 py-1 border rounded text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
                            >
                              <option value="">-</option>
                              {departments?.map((dept) => (
                                <option key={dept.id} value={dept.name}>{dept.name}</option>
                              ))}
                              <option value="__ADD_NEW__" className="font-semibold text-blue-600">➾ Ajouter...</option>
                            </select>
                          </TableCell>}
                          {!compactMode && <TableCell className="text-sm">
                            <select
                              value={invoice.isSubscription ? "OUI" : "NON"}
                              onChange={(e) => {
                                const newVal = e.target.value === "OUI" ? 1 : 0;
                                // Apprentissage : mémoriser la correction manuelle isSubscription
                                if (invoice.supplierName && newVal !== (invoice.isSubscription ?? 1)) {
                                  upsertLearningMutation.mutate({
                                    supplierName: invoice.supplierName,
                                    fieldName: 'isSubscription',
                                    originalValue: (invoice.isSubscription ?? 1) === 1 ? 'OUI' : 'NON',
                                    correctedValue: newVal === 1 ? 'OUI' : 'NON',
                                  });
                                }
                                updateFieldMutation.mutate({
                                  id: invoice.id,
                                  data: { isSubscription: newVal },
                                });
                              }}
                              className="w-full px-2 py-1 border rounded text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
                            >
                              <option value="NON">NON</option>
                              <option value="OUI">OUI</option>
                            </select>
                          </TableCell>}
                          <TableCell>{getQualityBadge(invoice.qualityScore)}</TableCell>
                          <TableCell>{getExportStatusBadge(invoice.exportStatus || "not_exported")}</TableCell>
                          <TableCell>
                            <div className="flex gap-2">
                              <Button
                                size="sm"
                                variant="outline"
                                onClick={() => {
                                  setSelectedInvoiceText(invoice.extractedText || "Aucun texte extrait disponible");
                                  setTextDialogOpen(true);
                                }}
                                className="h-8 px-2"
                                title="Voir le texte extrait"
                              >
                                <FileText className="h-4 w-4" />
                              </Button>
                              <Button
                                size="sm"
                                variant="outline"
                                onClick={() => setLocation(`/invoices/${invoice.id}`)}
                                className="h-8 px-2"
                                title="Modifier"
                              >
                                <Edit className="h-4 w-4" />
                              </Button>
                              <Button
                                size="sm"
                                variant="outline"
                                onClick={() => {
                                  setInvoiceToDelete(invoice.id);
                                  setDeleteDialogOpen(true);
                                }}
                                className="h-8 px-2 text-red-600 hover:text-red-700 hover:bg-red-50"
                                title="Supprimer"
                              >
                                <Trash className="h-4 w-4" />
                              </Button>
                            </div>
                          </TableCell>
                        </TableRow>
                      );
                    })}
                  </TableBody>
                </Table>
              </div>
            ) : (
              <div className="text-center py-12">
                <FileText className="w-12 h-12 mx-auto mb-3 text-gray-300" />
                <p className="text-gray-500">Aucune facture trouvée</p>
                <p className="text-sm text-gray-400 mt-1">
                  {searchQuery ? "Essayez une autre recherche" : "Commencez par importer un fichier PDF"}
                </p>
              </div>
            )}
          </CardContent>
        </Card>

        {/* Info message */}
        {filteredInvoices && filteredInvoices.some(inv => (inv.qualityScore || 0) < 100) && (
          <div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
            <p className="text-sm text-blue-800">
              <strong>Note :</strong> Seules les factures avec un score de qualité de 100% peuvent être exportées.
              Les factures avec un score inférieur sont grisées et ne peuvent pas être sélectionnées.
            </p>
          </div>
        )}
      </div>

      {/* Delete Confirmation Dialog */}
      <AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Êtes-vous sûr de vouloir supprimer cette facture ?</AlertDialogTitle>
            <AlertDialogDescription>
              Cette action est irréversible. La facture sera définitivement supprimée de la base de données.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel onClick={() => setInvoiceToDelete(null)}>Annuler</AlertDialogCancel>
            <AlertDialogAction
              onClick={() => {
                if (invoiceToDelete) {
                  deleteMutation.mutate({ id: invoiceToDelete });
                }
              }}
              className="bg-red-600 hover:bg-red-700"
            >
              Supprimer
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      {/* Add New Item Dialog */}
      <Dialog open={addDialogOpen} onOpenChange={setAddDialogOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>
              Ajouter {addDialogType === "service" ? "un nouveau service" : "une nouvelle ventilation"}
            </DialogTitle>
            <DialogDescription>
              Entrez le nom {addDialogType === "service" ? "du service" : "de la ventilation comptable"} à ajouter.
            </DialogDescription>
          </DialogHeader>
          <div className="py-4">
            <Input
              placeholder="Nom..."
              value={newItemName}
              onChange={(e) => setNewItemName(e.target.value)}
              onKeyDown={(e) => {
                if (e.key === "Enter") {
                  handleAddNewItem();
                }
              }}
              autoFocus
            />
          </div>
          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => {
                setAddDialogOpen(false);
                setNewItemName("");
                setPendingInvoiceId(null);
              }}
            >
              Annuler
            </Button>
            <Button onClick={handleAddNewItem}>Ajouter</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Extracted Text Dialog */}
      <Dialog open={textDialogOpen} onOpenChange={setTextDialogOpen}>
        <DialogContent className="max-w-3xl max-h-[80vh]">
          <DialogHeader>
            <DialogTitle>Texte extrait de la facture</DialogTitle>
            <DialogDescription>
              Texte complet extrait du PDF lors de l'import
            </DialogDescription>
          </DialogHeader>
          <div className="overflow-y-auto max-h-[60vh] p-4 bg-gray-50 rounded border">
            <pre className="whitespace-pre-wrap text-sm font-mono">{selectedInvoiceText}</pre>
          </div>
          <DialogFooter>
            <Button onClick={() => setTextDialogOpen(false)}>Fermer</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </DashboardLayout>
  );
}
