import { useState } from "react";
import { trpc } from "@/lib/trpc";
import DashboardLayout from "@/components/DashboardLayout";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { toast } from "sonner";
import {
  Loader2,
  CheckSquare,
  Search,
  Trash2,
  FolderOpen,
  Monitor,
  Calendar,
  User,
  Download,
  RefreshCw,
  Cloud,
  CloudOff,
  ExternalLink,
} from "lucide-react";

// Helper : télécharge un PDF annoté BAP depuis son URL de stockage
// pdfUrl peut être : '/storage/2026-04/BAP_xxx.pdf' ou '/storage/BAP_xxx.pdf'
// Nommage : AAAA-MM-JJ - Fournisseur - N°Facture.pdf
function downloadBapPdf(
  pdfUrl: string,
  supplierName?: string | null,
  invoiceNumber?: string | null,
  validatedAt?: Date | string | null
) {
  const fallback = pdfUrl.split('/').pop() || 'BAP.pdf';
  // Construire le nom de fichier : date - fournisseur - numero.pdf
  const datePart = validatedAt
    ? new Date(validatedAt).toLocaleDateString('fr-CA') // format AAAA-MM-JJ
    : '';
  const supplierPart = (supplierName || '').replace(/[^a-zA-Z0-9\u00e0-\u00ff \-]/g, '').trim();
  const numberPart = (invoiceNumber || '').replace(/[^a-zA-Z0-9\-]/g, '').trim();
  const parts = [datePart, supplierPart, numberPart].filter(Boolean);
  const filename = parts.length > 0 ? `${parts.join(' - ')}.pdf` : fallback;
  // Passer le filename au serveur pour qu'il soit dans Content-Disposition
  const downloadUrl = `/api/download-bap?pdfPath=${encodeURIComponent(pdfUrl)}&filename=${encodeURIComponent(filename)}`;
  const a = document.createElement('a');
  a.href = downloadUrl;
  a.download = filename;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
}

export default function BapHistory() {
  const { data: entries, isLoading, refetch } = trpc.bapHistory.getAll.useQuery();
  const deleteMutation = trpc.bapHistory.delete.useMutation();
  const regenerateMutation = trpc.bapHistory.regenerate.useMutation();
  const [search, setSearch] = useState("");
  const [regeneratingId, setRegeneratingId] = useState<number | null>(null);

  const handleRegenerate = async (id: number) => {
    setRegeneratingId(id);
    try {
      const result = await regenerateMutation.mutateAsync({ id });
      toast.success('PDF re-généré avec succès');
      refetch();
    } catch (err: any) {
      toast.error(err.message || 'Erreur lors de la re-génération du PDF');
    } finally {
      setRegeneratingId(null);
    }
  };

  const filtered = (entries || []).filter((e) => {
    const q = search.toLowerCase();
    return (
      !q ||
      (e.supplierName || "").toLowerCase().includes(q) ||
      (e.invoiceNumber || "").toLowerCase().includes(q) ||
      (e.serviceConcerne || "").toLowerCase().includes(q) ||
      (e.recipientName || "").toLowerCase().includes(q) ||
      (e.typeAchat || "").toLowerCase().includes(q)
    );
  });

  const handleDelete = async (id: number) => {
    try {
      await deleteMutation.mutateAsync({ id });
      toast.success("Entrée supprimée");
      refetch();
    } catch {
      toast.error("Impossible de supprimer cette entrée");
    }
  };

  const formatDate = (d: Date | string | null) => {
    if (!d) return "—";
    return new Date(d).toLocaleDateString("fr-FR", {
      day: "2-digit",
      month: "2-digit",
      year: "numeric",
      hour: "2-digit",
      minute: "2-digit",
    });
  };

  const formatAmount = (a: string | null) => {
    if (!a) return "—";
    const n = parseFloat(a);
    return isNaN(n) ? a : n.toLocaleString("fr-FR", { style: "currency", currency: "EUR" });
  };

  return (
    <DashboardLayout>
      <div className="max-w-7xl space-y-6">
        {/* Header */}
        <div className="space-y-2">
          <div className="flex items-center gap-3">
            <div className="p-3 bg-gradient-to-br from-green-500 to-emerald-600 rounded-xl shadow-lg">
              <CheckSquare className="w-7 h-7 text-white" />
            </div>
            <div>
              <h1 className="text-4xl font-bold bg-gradient-to-r from-green-600 to-emerald-600 bg-clip-text text-transparent">
                Historique BAP
              </h1>
              <p className="text-muted-foreground mt-1">
                Toutes les factures validées "Bon à Payer" avec leur PDF annoté
              </p>
            </div>
          </div>
        </div>

        {/* Stats rapides */}
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
          <Card className="border-green-200 dark:border-green-800">
            <CardContent className="pt-4 pb-3">
              <div className="text-2xl font-bold text-green-600">{(entries || []).length}</div>
              <div className="text-sm text-muted-foreground">Total validations</div>
            </CardContent>
          </Card>
          <Card className="border-blue-200 dark:border-blue-800">
            <CardContent className="pt-4 pb-3">
              <div className="text-2xl font-bold text-blue-600">
                {(entries || []).filter((e) => e.exportMode === "browser").length}
              </div>
              <div className="text-sm text-muted-foreground">Ouverts navigateur</div>
            </CardContent>
          </Card>
          <Card className="border-orange-200 dark:border-orange-800">
            <CardContent className="pt-4 pb-3">
              <div className="text-2xl font-bold text-orange-600">
                {(entries || []).filter((e) => e.exportMode === "folder").length}
              </div>
              <div className="text-sm text-muted-foreground">Exportés dossier</div>
            </CardContent>
          </Card>
          <Card className="border-purple-200 dark:border-purple-800">
            <CardContent className="pt-4 pb-3">
              <div className="text-2xl font-bold text-purple-600">
                {(entries || []).filter((e) => e.signatureName).length}
              </div>
              <div className="text-sm text-muted-foreground">Avec signature</div>
            </CardContent>
          </Card>
        </div>

        {/* Tableau */}
        <Card>
          <CardHeader className="border-b bg-gradient-to-r from-green-50 to-emerald-50 dark:from-green-950/20 dark:to-emerald-950/20">
            <div className="flex items-center justify-between gap-4 flex-wrap">
              <div>
                <CardTitle>Validations BAP</CardTitle>
                <CardDescription>
                  {filtered.length} résultat{filtered.length !== 1 ? "s" : ""}
                  {search ? ` pour "${search}"` : ""}
                </CardDescription>
              </div>
              <div className="relative w-72">
                <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                <Input
                  placeholder="Rechercher..."
                  value={search}
                  onChange={(e) => setSearch(e.target.value)}
                  className="pl-9 h-9"
                />
              </div>
            </div>
          </CardHeader>
          <CardContent className="p-0">
            {isLoading ? (
              <div className="flex items-center justify-center h-40 gap-3">
                <Loader2 className="w-6 h-6 animate-spin text-primary" />
                <span className="text-muted-foreground">Chargement...</span>
              </div>
            ) : filtered.length === 0 ? (
              <div className="flex flex-col items-center justify-center h-40 gap-2 text-muted-foreground">
                <CheckSquare className="w-10 h-10 opacity-30" />
                <p className="text-sm">
                  {search ? "Aucun résultat pour cette recherche" : "Aucune validation BAP enregistrée"}
                </p>
              </div>
            ) : (
              <div className="overflow-x-auto">
                <Table>
                  <TableHeader>
                    <TableRow className="bg-muted/30">
                      <TableHead className="w-36">
                        <div className="flex items-center gap-1">
                          <Calendar className="h-3.5 w-3.5" />
                          Date validation
                        </div>
                      </TableHead>
                      <TableHead>N° Facture</TableHead>
                      <TableHead>
                        <div className="flex items-center gap-1">
                          <User className="h-3.5 w-3.5" />
                          Destinataire
                        </div>
                      </TableHead>
                      <TableHead>Service</TableHead>
                      <TableHead>Signature</TableHead>
                      <TableHead>PDF</TableHead>
                      <TableHead className="w-28">Actions</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {filtered.map((entry) => (
                      <TableRow key={entry.id} className="hover:bg-muted/20">
                        <TableCell className="text-xs text-muted-foreground whitespace-nowrap">
                          {formatDate(entry.validatedAt)}
                        </TableCell>
                        <TableCell className="text-sm">
                          {entry.invoiceNumber || "—"}
                        </TableCell>
                        <TableCell className="text-sm max-w-[120px] truncate">
                          {entry.recipientName || (
                            <span className="text-muted-foreground italic text-xs">TOUS</span>
                          )}
                        </TableCell>
                        <TableCell className="text-sm max-w-[120px] truncate">
                          {entry.serviceConcerne || "—"}
                        </TableCell>
                        <TableCell className="text-sm">
                          {entry.signatureName ? (
                            <Badge variant="secondary" className="text-xs">
                              {entry.signatureName}
                            </Badge>
                          ) : (
                            <span className="text-muted-foreground text-xs">—</span>
                          )}
                        </TableCell>
                        <TableCell>
                          {entry.pdfUrl ? (
                            <div className="flex items-center gap-1">
                              <Button
                                variant="ghost"
                                size="sm"
                                className="h-7 px-2 text-blue-600 hover:text-blue-700"
                                onClick={() => window.open(entry.pdfUrl!, "_blank")}
                                title="Ouvrir dans le navigateur"
                              >
                                <Monitor className="h-3.5 w-3.5 mr-1" />
                                <span className="text-xs">Voir</span>
                              </Button>
                              <Button
                                variant="ghost"
                                size="sm"
                                className="h-7 px-2 text-emerald-600 hover:text-emerald-700 hover:bg-emerald-50"
                                onClick={() => downloadBapPdf(entry.pdfUrl!, entry.supplierName, entry.invoiceNumber, entry.validatedAt)}
                                title="Télécharger le PDF annoté"
                              >
                                <Download className="h-3.5 w-3.5" />
                              </Button>
                            </div>
                          ) : (entry as any).sharepointUploadStatus === 'success' ? (
                            <div className="flex items-center gap-1">
                              <div className="flex items-center gap-1 text-blue-600">
                                <Cloud className="h-3.5 w-3.5" />
                                <span className="text-xs">SharePoint</span>
                              </div>
                              {(entry as any).sharepointUploadPath && (
                                <a
                                  href={(entry as any).sharepointUploadPath}
                                  target="_blank"
                                  rel="noopener noreferrer"
                                  className="text-blue-500 hover:text-blue-700"
                                  title="Ouvrir dans SharePoint"
                                >
                                  <ExternalLink className="h-3.5 w-3.5" />
                                </a>
                              )}
                            </div>
                          ) : (entry as any).sharepointUploadStatus === 'error' ? (
                            <div
                              className="flex items-center gap-1 cursor-help"
                              title={(entry as any).sharepointUploadError || 'Erreur SharePoint'}
                            >
                              <div className="flex items-center gap-1 text-red-600 border border-red-200 bg-red-50 rounded px-1.5 py-0.5">
                                <CloudOff className="h-3.5 w-3.5 shrink-0" />
                                <span className="text-xs font-medium">SP Erreur</span>
                              </div>
                              {(entry as any).sharepointUploadError && (
                                <span
                                  className="hidden group-hover:block absolute z-50 max-w-xs bg-gray-900 text-white text-xs rounded p-2 shadow-lg"
                                >
                                  {(entry as any).sharepointUploadError}
                                </span>
                              )}
                            </div>
                          ) : entry.exportPath ? (
                            <div className="flex items-center gap-1">
                              <div className="flex items-center gap-1 text-orange-600">
                                <FolderOpen className="h-3.5 w-3.5" />
                                <span className="text-xs truncate max-w-[80px]" title={entry.exportPath}>Dossier</span>
                              </div>
                              {/* Bouton Re-générer si le PDF de dossier n'est plus accessible */}
                              <Button
                                variant="ghost"
                                size="sm"
                                className="h-7 px-2 text-violet-600 hover:text-violet-700 hover:bg-violet-50"
                                onClick={() => handleRegenerate(entry.id)}
                                disabled={regeneratingId === entry.id}
                                title="Re-générer le PDF annoté"
                              >
                                {regeneratingId === entry.id ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <RefreshCw className="h-3.5 w-3.5" />}
                              </Button>
                            </div>
                          ) : (
                            <div className="flex items-center gap-1">
                              <span className="text-muted-foreground text-xs">—</span>
                              <Button
                                variant="ghost"
                                size="sm"
                                className="h-7 px-2 text-violet-600 hover:text-violet-700 hover:bg-violet-50"
                                onClick={() => handleRegenerate(entry.id)}
                                disabled={regeneratingId === entry.id}
                                title="Re-générer le PDF annoté"
                              >
                                {regeneratingId === entry.id ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <RefreshCw className="h-3.5 w-3.5 mr-1" />}
                                <span className="text-xs">Re-générer</span>
                              </Button>
                            </div>
                          )}
                        </TableCell>
                        <TableCell>
                          <div className="flex items-center gap-1">
                            {/* Bouton Réexporter (re-télécharger) */}
                            {entry.pdfUrl && (
                              <Button
                                variant="ghost"
                                size="sm"
                                className="h-7 px-2 text-amber-600 hover:text-amber-700 hover:bg-amber-50"
                                onClick={() => downloadBapPdf(entry.pdfUrl!, entry.supplierName, entry.invoiceNumber, entry.validatedAt)}
                                title="Réexporter le PDF annoté"
                              >
                                <RefreshCw className="h-3.5 w-3.5 mr-1" />
                                <span className="text-xs">Réexporter</span>
                              </Button>
                            )}
                            {/* Bouton Re-générer (recréer le PDF annoté depuis la base) */}
                            <Button
                              variant="ghost"
                              size="sm"
                              className="h-7 px-2 text-violet-600 hover:text-violet-700 hover:bg-violet-50"
                              onClick={() => handleRegenerate(entry.id)}
                              disabled={regeneratingId === entry.id}
                              title="Re-générer le PDF annoté depuis les données en base"
                            >
                              {regeneratingId === entry.id
                                ? <Loader2 className="h-3.5 w-3.5 animate-spin" />
                                : <RefreshCw className="h-3.5 w-3.5" />}
                            </Button>
                            {/* Bouton Supprimer */}
                            <Button
                              variant="ghost"
                              size="sm"
                              className="h-7 w-7 p-0 text-destructive hover:text-destructive hover:bg-destructive/10"
                              onClick={() => handleDelete(entry.id)}
                              disabled={deleteMutation.isPending}
                            >
                              <Trash2 className="h-3.5 w-3.5" />
                            </Button>
                          </div>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            )}
          </CardContent>
        </Card>
      </div>
    </DashboardLayout>
  );
}
