import { useAuth } from "@/_core/hooks/useAuth";
import { AuthenticatedPageSkeleton } from "@/components/AuthenticatedPageSkeleton";
import { EmptyStateCard } from "@/components/EmptyStateCard";
import { PortalActionGroup, PortalDashboardHeader, PortalSectionIntro, PortalSurface } from "@/components/portal/PortalSurface";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { buildRoutePrefetchHandlers } from "@/lib/routePrefetch";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Textarea } from "@/components/ui/textarea";
import { trpc } from "@/lib/trpc";
import { getFriendlyActionError } from "@/lib/userFeedback";
import { CheckCircle, Download, ExternalLink, FileText, FolderOpen, Loader2, MoreHorizontal, Plus, Send, Trash2, Upload, XCircle } from "lucide-react";
import { useMemo, useRef, useState, type ReactNode } from "react";
import { Link, useLocation } from "wouter";
import { toast } from "sonner";

const documentTypes = [
  { value: 'statuts', label: 'Statuts' },
  { value: 'recepisse_declaration', label: 'Récépissé de déclaration' },
  { value: 'rib', label: 'RIB' },
  { value: 'rapport_activite', label: 'Rapport d\'activité' },
  { value: 'rapport_financier', label: 'Rapport financier' },
  { value: 'pv_assemblee', label: 'PV d\'assemblée générale' },
  { value: 'liste_dirigeants', label: 'Liste des dirigeants' },
  { value: 'attestation_assurance', label: 'Attestation d\'assurance' },
  { value: 'autre', label: 'Autre' },
];

type DocumentType = typeof documentTypes[number]['value'];

type SalleWorkflowQuoteStatus = "a_preparer" | "en_attente_association" | "accepte" | "refuse";
type SalleWorkflowDirectorStatus = "a_transmettre" | "en_attente_signature" | "signee";

type GeneratedSalleDocument = {
  requestId: number;
  requestTitle: string;
  requestStatus: string;
  associationName: string;
  quoteStatus: SalleWorkflowQuoteStatus;
  directorStatus: SalleWorkflowDirectorStatus;
  finalNotificationSentAt: string;
  quotePdfUrl: string;
  quotePdfName: string;
  decisionPdfUrl: string;
  decisionPdfName: string;
};

function parseGeneratedSalleDocument(request: any): GeneratedSalleDocument | null {
  if (request?.type !== "demande_salle") return null;

  try {
    const formData = request.formData ? JSON.parse(request.formData) : {};
    const workflow = formData?.salleWorkflow;
    if (!workflow || typeof workflow !== "object") return null;

    const quotePdfUrl = typeof workflow.quotePdfUrl === "string" ? workflow.quotePdfUrl : "";
    const quotePdfName = typeof workflow.quotePdfName === "string" ? workflow.quotePdfName : "";
    const decisionPdfUrl = typeof workflow.administrativeDecisionPdfUrl === "string" ? workflow.administrativeDecisionPdfUrl : "";
    const decisionPdfName = typeof workflow.administrativeDecisionPdfName === "string" ? workflow.administrativeDecisionPdfName : "";
    const quoteStatus = typeof workflow.quoteStatus === "string" ? workflow.quoteStatus as SalleWorkflowQuoteStatus : "a_preparer";
    const directorStatus = typeof workflow.directorStatus === "string" ? workflow.directorStatus as SalleWorkflowDirectorStatus : "a_transmettre";
    const finalNotificationSentAt = typeof workflow.finalNotificationSentAt === "string" ? workflow.finalNotificationSentAt : "";

    if (!quotePdfUrl && !decisionPdfUrl && quoteStatus !== "en_attente_association" && directorStatus === "a_transmettre" && !finalNotificationSentAt) {
      return null;
    }

    return {
      requestId: request.id,
      requestTitle: request.titre,
      requestStatus: request.status,
      associationName: request.nomAssociation || request.associationName || "Association",
      quoteStatus,
      directorStatus,
      finalNotificationSentAt,
      quotePdfUrl,
      quotePdfName,
      decisionPdfUrl,
      decisionPdfName,
    };
  } catch {
    return null;
  }
}

function getSalleWorkflowDocumentState(entry: GeneratedSalleDocument) {
  if (entry.finalNotificationSentAt) {
    return {
      label: "Demande finalisée",
      description: "Le formulaire signé, la décision et la facture ont été envoyés à l’association.",
      className: "bg-green-100 text-green-700 border-green-200",
    };
  }
  if (entry.directorStatus === "en_attente_signature") {
    return {
      label: "En signature Direction",
      description: "Le dossier complet a été transmis pour signature.",
      className: "bg-amber-100 text-amber-800 border-amber-200",
    };
  }
  if (entry.quoteStatus === "accepte") {
    return {
      label: "Devis accepté",
      description: "Votre validation a été enregistrée. L’hôtesse transmet ou suit maintenant la signature Direction.",
      className: "bg-blue-100 text-blue-700 border-blue-200",
    };
  }
  if (entry.quoteStatus === "refuse") {
    return {
      label: "Refus transmis",
      description: "Votre refus a été enregistré et transmis à l’hôtesse.",
      className: "bg-red-100 text-red-700 border-red-200",
    };
  }
  if (entry.quoteStatus === "en_attente_association") {
    return {
      label: "Réponse au devis attendue",
      description: "Les documents générés sont disponibles. Vous pouvez maintenant valider ou refuser la demande.",
      className: "bg-violet-100 text-violet-700 border-violet-200",
    };
  }
  if (entry.requestStatus === "en_cours_traitement" || entry.requestStatus === "information_complementaire") {
    return {
      label: "Analyse hôtesse",
      description: "Votre demande est en cours d’analyse par l’hôtesse d’accueil.",
      className: "bg-yellow-100 text-yellow-800 border-yellow-200",
    };
  }
  return {
    label: "Soumis",
    description: "Votre demande a bien été déposée.",
    className: "bg-blue-100 text-blue-700 border-blue-200",
  };
}

function DocumentsOverflowMenu({
  label = "Autres actions",
  children,
}: {
  label?: string;
  children: ReactNode;
}) {
  return (
    <DropdownMenu>
      <DropdownMenuTrigger asChild>
        <Button variant="outline" size="sm" className="h-11 w-11 p-0 sm:h-9 sm:w-9" aria-label={label}>
          <MoreHorizontal className="h-4 w-4" />
        </Button>
      </DropdownMenuTrigger>
      <DropdownMenuContent align="end" className="w-56">
        {children}
      </DropdownMenuContent>
    </DropdownMenu>
  );
}

export default function Documents() {
  const [, setLocation] = useLocation();
  const { data: documents, isLoading } = trpc.document.getMyDocuments.useQuery();
  const { data: requests, isLoading: requestsLoading } = trpc.request.getMyRequests.useQuery();
  const { data: association } = trpc.association.getMyProfile.useQuery();
  const utils = trpc.useUtils();
  const returnTo = useMemo(() => {
    if (typeof window === "undefined") return null;
    const value = new URLSearchParams(window.location.search).get("returnTo");
    return value?.startsWith("/dashboard/") ? value : null;
  }, []);

  const [isUploadOpen, setIsUploadOpen] = useState(false);
  const [uploadData, setUploadData] = useState({
    nom: '',
    type: 'autre' as DocumentType,
    description: '',
  });
  const [selectedFile, setSelectedFile] = useState<File | null>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);

  const uploadMutation = trpc.document.upload.useMutation({
    onSuccess: () => {
      toast.success('Document téléversé avec succès');
      utils.document.getMyDocuments.invalidate();
      setIsUploadOpen(false);
      setUploadData({ nom: '', type: 'autre', description: '' });
      setSelectedFile(null);
    },
    onError: (error) => {
      toast.error(
        getFriendlyActionError(
          error,
          "Impossible de téléverser le document pour le moment. Vérifiez le fichier puis réessayez.",
          {
            invalidInputMessage:
              "Impossible de téléverser le document : merci de renseigner le nom, le type et un fichier valide.",
          }
        )
      );
    },
  });

  const deleteMutation = trpc.document.delete.useMutation({
    onSuccess: () => {
      toast.success('Document supprimé');
      utils.document.getMyDocuments.invalidate();
    },
    onError: (error) => {
      toast.error(
        getFriendlyActionError(
          error,
          "Impossible de supprimer ce document pour le moment."
        )
      );
    },
  });

  const respondSalleQuoteMutation = trpc.request.respondSalleQuote.useMutation({
    onSuccess: (data) => {
      toast.success(
        data.quoteStatus === "accepte"
          ? "Votre accord a bien été enregistré. Le dossier repart vers l’hôtesse."
          : "Votre refus a bien été enregistré."
      );
      utils.request.getMyRequests.invalidate();
    },
    onError: (error) => {
      toast.error(
        getFriendlyActionError(
          error,
          "Impossible d'enregistrer votre réponse pour le moment. Vérifiez votre session puis réessayez."
        )
      );
    },
  });

  const generatedSalleDocuments = useMemo(
    () => (requests || []).map(parseGeneratedSalleDocument).filter((entry): entry is GeneratedSalleDocument => Boolean(entry)),
    [requests]
  );

  const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      setSelectedFile(file);
      if (!uploadData.nom) {
        setUploadData(prev => ({ ...prev, nom: file.name.replace(/\.[^/.]+$/, '') }));
      }
    }
  };

  const handleUpload = async () => {
    if (!selectedFile || !uploadData.nom || !uploadData.type) {
      toast.error('Veuillez remplir tous les champs obligatoires');
      return;
    }

    // Convert file to base64
    const reader = new FileReader();
    reader.onload = () => {
      const base64 = (reader.result as string).split(',')[1];
      uploadMutation.mutate({
        nom: uploadData.nom,
        type: uploadData.type as any,
        description: uploadData.description,
        fileData: base64,
        fileName: selectedFile.name,
        mimeType: selectedFile.type || 'application/octet-stream',
      });
    };
    reader.readAsDataURL(selectedFile);
  };

  const handleDownload = async (doc: { id: number; nom: string; fileUrl: string }) => {
    window.open(doc.fileUrl, '_blank');
  };

  const formatFileSize = (bytes: number | null) => {
    if (!bytes) return '-';
    if (bytes < 1024) return `${bytes} B`;
    if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
    return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
  };

  const formatDate = (date: Date | string) => {
    return new Date(date).toLocaleDateString('fr-FR', {
      day: '2-digit',
      month: '2-digit',
      year: 'numeric',
    });
  };

  if (!association) {
    return (
      <div className="portal-immersive-page min-h-screen">
        <PortalDashboardHeader
          tourId="documents-header"
          title="Mes documents"
        />
        <main className="container py-8">
          <Card className="max-w-md mx-auto">
            <CardHeader>
              <CardTitle>Profil requis</CardTitle>
              <CardDescription>
                Veuillez d'abord compléter votre profil association pour pouvoir gérer vos documents.
              </CardDescription>
            </CardHeader>
            <CardContent>
              <Link href="/dashboard/profile" {...buildRoutePrefetchHandlers("/dashboard/profile")}>
                <Button className="w-full">Créer mon profil</Button>
              </Link>
            </CardContent>
          </Card>
        </main>
      </div>
    );
  }

  return (
    <div className="portal-immersive-page min-h-screen">
      <PortalDashboardHeader
        tourId="documents-header"
        title="Mes documents"
        description={
          returnTo
            ? "Votre demande en cours est conservée. Vous pouvez y revenir quand vous voulez."
            : `${documents?.length || 0} document(s) stocké(s)`
        }
        actions={
          <PortalActionGroup className="w-full sm:w-auto">
            {returnTo ? (
              <Button variant="outline" onClick={() => setLocation(returnTo)} className="min-h-11 w-full sm:w-auto">
                Revenir à ma demande en cours
              </Button>
            ) : null}
            <Dialog open={isUploadOpen} onOpenChange={setIsUploadOpen}>
              <DialogTrigger asChild>
                <Button data-tour-id="documents-upload" className="min-h-11 w-full sm:w-auto">
                  <Plus className="mr-2 h-4 w-4" />
                  Ajouter un document
                </Button>
              </DialogTrigger>
              <DialogContent>
                <DialogHeader>
                  <DialogTitle>Téléverser un document</DialogTitle>
                  <DialogDescription>
                    Ajoutez un nouveau document à votre espace association.
                  </DialogDescription>
                </DialogHeader>
                <div className="space-y-4 py-4">
                  <div className="space-y-2">
                    <Label>Fichier *</Label>
                    <div 
                      className="border-2 border-dashed border-border rounded-lg p-6 text-center cursor-pointer hover:border-primary/50 transition-colors"
                      onClick={() => fileInputRef.current?.click()}
                    >
                      {selectedFile ? (
                        <div className="flex items-center justify-center gap-2">
                          <FileText className="h-8 w-8 text-primary" />
                          <div className="text-left">
                            <p className="font-medium">{selectedFile.name}</p>
                            <p className="text-sm text-muted-foreground">
                              {formatFileSize(selectedFile.size)}
                            </p>
                          </div>
                        </div>
                      ) : (
                        <>
                          <Upload className="h-8 w-8 mx-auto text-muted-foreground mb-2" />
                          <p className="text-sm text-muted-foreground">
                            Cliquez pour sélectionner un fichier
                          </p>
                        </>
                      )}
                    </div>
                    <input
                      ref={fileInputRef}
                      type="file"
                      className="hidden"
                      onChange={handleFileSelect}
                      accept=".pdf,.doc,.docx,.jpg,.jpeg,.png,.xls,.xlsx"
                    />
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor="docName">Nom du document *</Label>
                    <Input
                      id="docName"
                      value={uploadData.nom}
                      onChange={(e) => setUploadData(prev => ({ ...prev, nom: e.target.value }))}
                      placeholder="Ex: Statuts 2024"
                    />
                  </div>

                  <div className="space-y-2">
                    <Label>Type de document *</Label>
                    <Select
                      value={uploadData.type}
                      onValueChange={(value) => setUploadData(prev => ({ ...prev, type: value as DocumentType }))}
                    >
                      <SelectTrigger>
                        <SelectValue placeholder="Sélectionnez un type" />
                      </SelectTrigger>
                      <SelectContent>
                        {documentTypes.map(type => (
                          <SelectItem key={type.value} value={type.value}>
                            {type.label}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor="docDescription">Description (optionnel)</Label>
                    <Textarea
                      id="docDescription"
                      value={uploadData.description}
                      onChange={(e) => setUploadData(prev => ({ ...prev, description: e.target.value }))}
                      placeholder="Ajoutez une description..."
                      rows={2}
                    />
                  </div>
                </div>
                <DialogFooter>
                  <Button variant="outline" onClick={() => setIsUploadOpen(false)}>
                    Annuler
                  </Button>
                  <Button onClick={handleUpload} disabled={uploadMutation.isPending}>
                    {uploadMutation.isPending ? (
                      <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                    ) : (
                      <Upload className="mr-2 h-4 w-4" />
                    )}
                    {uploadMutation.isPending ? "Téléversement en cours..." : "Téléverser"}
                  </Button>
                </DialogFooter>
              </DialogContent>
            </Dialog>
          </PortalActionGroup>
        }
      />

      <main className="container py-8">
        {isLoading || requestsLoading ? (
          <div className="mx-auto max-w-5xl">
            <AuthenticatedPageSkeleton
              hero={false}
              message="Chargement de vos documents téléversés et des documents générés liés à vos demandes..."
              cards={2}
              formRows={3}
            />
          </div>
        ) : documents && (documents.length > 0 || generatedSalleDocuments.length > 0) ? (
          <div className="space-y-8">
            <PortalSurface
              className="border-primary/10 bg-gradient-to-r from-primary/10 via-white to-primary/5"
              bodyClassName="space-y-4"
            >
              <PortalSectionIntro
                eyebrow="Suivi"
                title="Documents générés"
                description="Retrouvez ici les pièces produites pendant le workflow devis / signature et répondez directement si une validation est attendue."
                aside="Consultez, téléchargez ou revenez dans votre dossier sans perdre le fil."
              />
            </PortalSurface>
            <section className="space-y-4">
              {generatedSalleDocuments.length > 0 ? (
                <div className="grid gap-4">
                  {generatedSalleDocuments.map((entry) => {
                    const workflowState = getSalleWorkflowDocumentState(entry);
                    const canRespond = entry.quoteStatus === "en_attente_association";

	                    return (
	                      <Card key={`generated-${entry.requestId}`} className="overflow-hidden rounded-2xl border border-border/70 bg-white/95 transition-all duration-200 hover:-translate-y-0.5 hover:shadow-md">
	                        <CardContent className="p-5 space-y-4">
	                          <div className="rounded-2xl border border-primary/10 bg-gradient-to-r from-primary/10 via-white to-primary/5 p-4">
	                            <div className="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
	                              <div className="space-y-3">
	                                <div className="flex items-center gap-2 flex-wrap">
	                                  <span className="rounded-full border border-primary/15 bg-white/80 px-2.5 py-1 text-[11px] font-semibold uppercase tracking-[0.14em] text-primary">
	                                    Pièces générées
	                                  </span>
	                                  <span className={`rounded-full px-2.5 py-1 text-xs font-medium border ${workflowState.className}`}>
	                                    {workflowState.label}
	                                  </span>
	                                </div>
	                                <div className="space-y-2">
	                                  <h3 className="text-lg font-semibold text-slate-950">{entry.requestTitle}</h3>
	                                  <p className="text-sm text-muted-foreground">{workflowState.description}</p>
	                                </div>
	                              </div>
	                              <Link href={`/dashboard/requests/${entry.requestId}`} className="w-full lg:w-auto" {...buildRoutePrefetchHandlers(`/dashboard/requests/${entry.requestId}`)}>
	                                <Button variant="outline" size="sm" className="min-h-11 w-full lg:w-auto">
	                                  <Send className="mr-2 h-4 w-4" />
	                                  Voir la demande
	                                </Button>
	                              </Link>
	                            </div>
	                            <div className="mt-4 grid gap-3 sm:grid-cols-3">
	                              <div className="rounded-xl border border-white/80 bg-white/90 px-3 py-3">
	                                <p className="text-[11px] uppercase tracking-wide text-muted-foreground">Association</p>
	                                <p className="mt-1 text-sm font-semibold text-slate-950">{entry.associationName}</p>
	                              </div>
	                              <div className="rounded-xl border border-white/80 bg-white/90 px-3 py-3">
	                                <p className="text-[11px] uppercase tracking-wide text-muted-foreground">Devis</p>
	                                <p className="mt-1 text-sm font-semibold text-slate-950">
	                                  {entry.quoteStatus === "en_attente_association" ? "Réponse attendue" : entry.quoteStatus === "accepte" ? "Accepté" : entry.quoteStatus === "refuse" ? "Refusé" : "En préparation"}
	                                </p>
	                              </div>
	                              <div className="rounded-xl border border-white/80 bg-white/90 px-3 py-3">
	                                <p className="text-[11px] uppercase tracking-wide text-muted-foreground">Décision</p>
	                                <p className="mt-1 text-sm font-semibold text-slate-950">
	                                  {entry.decisionPdfUrl ? "Disponible" : entry.directorStatus === "en_attente_signature" ? "En signature" : "À venir"}
	                                </p>
	                              </div>
	                            </div>
	                          </div>

	                          <div className="space-y-4">
	                            <p className="text-sm text-muted-foreground">
	                              Gardez l’action principale sous la main et retrouvez les téléchargements complémentaires dans le menu secondaire.
                            </p>
                            <div className="grid gap-3 sm:grid-cols-2">
                            {entry.quotePdfUrl ? (
                              <div className="rounded-xl border border-slate-200 bg-white px-4 py-4 shadow-[0_12px_28px_-24px_rgba(15,23,42,0.22)]">
                                <div className="space-y-1">
                                  <p className="text-sm font-semibold text-slate-950">Devis</p>
                                  <p className="text-sm text-muted-foreground break-words">{entry.quotePdfName || "Document généré"}</p>
                                </div>
                                <div className="mt-4 flex items-center gap-2">
                                  <Link className="min-w-0 flex-1" href={`/dashboard/requests/${entry.requestId}/salle-document/devis?returnTo=${encodeURIComponent("/dashboard/documents")}`} {...buildRoutePrefetchHandlers(`/dashboard/requests/${entry.requestId}`)}>
                                    <Button variant="outline" size="sm" className="h-10 w-full justify-start sm:justify-center">
                                      <ExternalLink className="mr-2 h-4 w-4" />
                                      Voir le devis
                                    </Button>
                                  </Link>
                                  <DocumentsOverflowMenu label="Actions du devis">
                                    <DropdownMenuItem asChild>
                                      <Link href={`/dashboard/requests/${entry.requestId}/salle-document/devis?returnTo=${encodeURIComponent("/dashboard/documents")}`}>
                                        <Download className="h-4 w-4" />
                                        Télécharger le devis
                                      </Link>
                                    </DropdownMenuItem>
                                  </DocumentsOverflowMenu>
                                </div>
                              </div>
                            ) : null}

                            {entry.decisionPdfUrl ? (
                              <div className="rounded-xl border border-slate-200 bg-white px-4 py-4 shadow-[0_12px_28px_-24px_rgba(15,23,42,0.22)]">
                                <div className="space-y-1">
                                  <p className="text-sm font-semibold text-slate-950">Décision administrative</p>
                                  <p className="text-sm text-muted-foreground break-words">{entry.decisionPdfName || "Document généré"}</p>
                                </div>
                                <div className="mt-4 flex items-center gap-2">
                                  <Link className="min-w-0 flex-1" href={`/dashboard/requests/${entry.requestId}/salle-document/decision?returnTo=${encodeURIComponent("/dashboard/documents")}`} {...buildRoutePrefetchHandlers(`/dashboard/requests/${entry.requestId}`)}>
                                    <Button variant="outline" size="sm" className="h-10 w-full justify-start sm:justify-center">
                                      <ExternalLink className="mr-2 h-4 w-4" />
                                      Voir la décision
                                    </Button>
                                  </Link>
                                  <DocumentsOverflowMenu label="Actions de la décision">
                                    <DropdownMenuItem asChild>
                                      <Link href={`/dashboard/requests/${entry.requestId}/salle-document/decision?returnTo=${encodeURIComponent("/dashboard/documents")}`}>
                                        <Download className="h-4 w-4" />
                                        Télécharger la décision
                                      </Link>
                                    </DropdownMenuItem>
                                  </DocumentsOverflowMenu>
                                </div>
                              </div>
                            ) : null}
                          </div>
                          </div>

                          {canRespond ? (
                            <div className="rounded-lg border border-primary/20 bg-primary/5 p-4 space-y-3">
                              <p className="text-sm font-medium">Votre réponse est attendue</p>
                              <div className="flex flex-wrap gap-3">
                                <Button
                                  onClick={() => respondSalleQuoteMutation.mutate({ id: entry.requestId, decision: "accepte" })}
                                  disabled={respondSalleQuoteMutation.isPending}
                                >
                                  {respondSalleQuoteMutation.isPending ? (
                                    <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                                  ) : (
                                    <CheckCircle className="mr-2 h-4 w-4" />
                                  )}
                                  J’accepte le devis
                                </Button>
                                <Button
                                  variant="destructive"
                                  onClick={() => respondSalleQuoteMutation.mutate({ id: entry.requestId, decision: "refuse" })}
                                  disabled={respondSalleQuoteMutation.isPending}
                                >
                                  {respondSalleQuoteMutation.isPending ? (
                                    <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                                  ) : (
                                    <XCircle className="mr-2 h-4 w-4" />
                                  )}
                                  Je refuse le devis
                                </Button>
                              </div>
                            </div>
                          ) : null}
                        </CardContent>
                      </Card>
                    );
                  })}
                </div>
              ) : (
                <EmptyStateCard
                  icon={FileText}
                  title="Aucun document généré pour le moment"
                  description="Les devis, décisions et autres pièces produites pendant le traitement apparaîtront ici dès qu’un dossier avancera dans le workflow."
                />
              )}
            </section>

            <section className="space-y-4">
              <PortalSectionIntro
                eyebrow="Référentiel"
                title="Documents téléversés"
                description="Vos documents administratifs et pièces jointes stockés dans votre espace."
                aside={
                  <div className="flex items-center gap-2 text-emerald-900">
                    <span className="inline-flex min-w-8 items-center justify-center rounded-full bg-emerald-100 px-2.5 py-1 text-sm font-semibold">
                      {documents.length}
                    </span>
                    <span className="font-medium">
                      {documents.length > 1 ? "documents disponibles" : documents.length === 1 ? "document disponible" : "aucun document"}
                    </span>
                  </div>
                }
                className="rounded-2xl border border-emerald-200/90 bg-gradient-to-r from-emerald-50/95 via-white to-sky-50/70 px-4 py-4 shadow-[0_16px_38px_-24px_rgba(16,24,40,0.18)] sm:px-5"
                eyebrowClassName="text-emerald-800"
                titleClassName="text-slate-950"
                descriptionClassName="text-[0.97rem] font-medium leading-6 text-slate-700"
              />
              {documents.length > 0 ? (
                <div className="grid gap-4">
                  {documents.map(doc => (
	                      <Card key={doc.id} className="overflow-hidden rounded-2xl border border-border/70 bg-white/95 transition-all duration-200 hover:-translate-y-0.5 hover:shadow-md">
	                        <CardContent className="p-4 sm:p-5">
	                          <div className="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
	                            <div className="flex min-w-0 items-start gap-4">
                            <div className="flex h-12 w-12 shrink-0 items-center justify-center rounded-lg bg-primary/10">
                              <FileText className="h-6 w-6 text-primary" />
                            </div>
	                              <div className="min-w-0 flex-1">
	                                <div className="mb-3 flex flex-wrap items-center gap-2">
	                                  <span className="rounded-full border border-primary/15 bg-primary/5 px-2.5 py-1 text-[11px] font-semibold uppercase tracking-[0.14em] text-primary">
	                                    Document stocké
	                                  </span>
	                                  <span className="rounded-full bg-slate-100 px-2 py-1 text-[11px] font-medium text-slate-700">
	                                    {documentTypes.find(t => t.value === doc.type)?.label || doc.type}
	                                  </span>
	                                </div>
	                                <h3 className="break-words text-base font-medium leading-6">{doc.nom}</h3>
	                                <div className="mt-2 flex flex-wrap items-center gap-x-3 gap-y-2 text-sm text-muted-foreground">
	                                  <span>{formatFileSize(doc.fileSize)}</span>
	                                  <span>{formatDate(doc.uploadedAt)}</span>
	                                </div>
                              {doc.description && (
                                <p className="mt-2 text-sm leading-6 text-muted-foreground">{doc.description}</p>
                              )}
                            </div>
                          </div>
                          <div className="flex w-full items-center justify-end gap-2 sm:w-auto sm:justify-start">
                            <Button
                              variant="outline"
                              size="icon"
                              className="h-11 w-11 shrink-0"
                              onClick={() => handleDownload(doc)}
                            >
                              <Download className="h-4 w-4" />
                            </Button>
                            <Button
                              variant="outline"
                              size="icon"
                              className="h-11 w-11 shrink-0 text-destructive hover:text-destructive"
                              onClick={() => {
                                if (confirm('Êtes-vous sûr de vouloir supprimer ce document ?')) {
                                  deleteMutation.mutate({ id: doc.id });
                                }
                              }}
                            >
                              <Trash2 className="h-4 w-4" />
                            </Button>
                          </div>
                        </div>
                      </CardContent>
                    </Card>
                  ))}
                </div>
              ) : (
                <EmptyStateCard
                  icon={FolderOpen}
                  title="Aucun document téléversé pour le moment"
                  description="Ajoutez vos pièces administratives ici pour les retrouver facilement lors de vos futures demandes."
                  actionLabel="Ajouter un document"
                  onAction={() => setIsUploadOpen(true)}
                />
              )}
            </section>
          </div>
        ) : (
          <div className="mx-auto max-w-4xl">
            <EmptyStateCard
              icon={FolderOpen}
              title="Votre espace documentaire est encore vide"
              description="Commencez par téléverser vos documents administratifs. Ils resteront disponibles pour vos prochaines demandes et pour le suivi des dossiers déjà transmis."
              actionLabel="Ajouter un document"
              onAction={() => setIsUploadOpen(true)}
            />
          </div>
        )}
      </main>
    </div>
  );
}
