import { useAuth } from "@/_core/hooks/useAuth";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Separator } from "@/components/ui/separator";
import {
  buildReservationSallePayload,
  listReservationDates,
  parseReservationSallePayload,
  sallesMJS,
  syncReservationSalleDailySlots,
  validateReservationSalleFormInput,
} from "@/lib/reservationSalle";
import {
  emptyMaterialEventQuantities,
  emptyMaterialEventSelection,
  materialEventItems,
  type MaterialEventItemKey,
} from "@/lib/materialEvent";
import { trpc } from "@/lib/trpc";
import { ArrowLeft, Building2, CalendarDays, CheckCircle, FileText, Loader2, Paperclip, Save, Send, Trash2, Upload } from "lucide-react";
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger } from "@/components/ui/alert-dialog";
import { useEffect, useMemo, useState } from "react";
import { Link, useParams, useLocation } from "wouter";
import { toast } from "sonner";

const requestTypeLabels: Record<string, string> = {
  subvention_fonctionnement: 'Subvention de fonctionnement',
  subvention_projet: 'Subvention de projet',
  agrement_jeunesse_education: 'Agrément Jeunesse et Éducation Populaire',
  agrement_sport: 'Agrément Sport',
  autorisation_occupation: 'Autorisation d\'occupation',
  demande_salle: 'Demande de salle',
  demande_materiel_evenementiel: 'Demande du matériel événementiel',
  autre: 'Autre demande',
};

function getTodayDateString() {
  return new Date().toISOString().split("T")[0];
}

function getSalleWorkflowQuoteStatus(formDataRaw: string | null | undefined): string | null {
  try {
    const formData = formDataRaw ? JSON.parse(formDataRaw) : {};
    return typeof formData?.salleWorkflow?.quoteStatus === "string" ? formData.salleWorkflow.quoteStatus : null;
  } catch {
    return null;
  }
}

function getSalleWorkflowLockState(formDataRaw: string | null | undefined) {
  try {
    const formData = formDataRaw ? JSON.parse(formDataRaw) : {};
    const workflow = formData?.salleWorkflow;
    return {
      quoteStatus: typeof workflow?.quoteStatus === "string" ? workflow.quoteStatus : null,
      directorStatus: typeof workflow?.directorStatus === "string" ? workflow.directorStatus : null,
      finalNotificationSentAt:
        typeof workflow?.finalNotificationSentAt === "string" ? workflow.finalNotificationSentAt : null,
    };
  } catch {
    return {
      quoteStatus: null,
      directorStatus: null,
      finalNotificationSentAt: null,
    };
  }
}

export default function EditRequest() {
  const params = useParams<{ id: string }>();
  const [, setLocation] = useLocation();
  const requestId = parseInt(params.id || '0');

  const { data: request, isLoading: requestLoading } = trpc.request.getById.useQuery(
    { id: requestId },
    { enabled: requestId > 0 }
  );
  const { data: association } = trpc.association.getMyProfile.useQuery();
  const { data: documents } = trpc.document.getMyDocuments.useQuery();
  const { data: logisticsPolicy } = trpc.request.getLogisticsPolicy.useQuery();
  const utils = trpc.useUtils();
  const restitutionGraceDays = logisticsPolicy?.materialReturnGraceDays ?? 3;

  const [formData, setFormData] = useState({
    titre: '',
    description: '',
    montantDemande: '',
    objetProjet: '',
    dateDebut: '',
    dateFin: '',
    publicVise: '',
    commune: '',
    direction: '',
    service: '',
    demandeurNomPrenom: '',
    dateDemande: '',
    dateDebutManifestation: '',
    dateFinManifestation: '',
    motifDemande: '',
    datePriseEnCharge: '',
    dateRestitution: '',
    autreMaterielPrecisions: '',
    dgsSignataire: '',
    motifReservation: '',
    dateReservation: '',
    dateFinReservation: '',
    heureDebut: '',
    heureFin: '',
    useDetailedSchedule: false,
    horairesParJour: [] as { date: string; heureDebut: string; heureFin: string }[],
    typeUsage: 'conventionne' as 'conventionne' | 'occasionnel',
    frequence: 'journee' as 'demi_journee' | 'journee' | 'mensuel',
    nombreParticipants: '',
    besoinsComplementaires: '',
    materielNecessaire: '',
    observations: '',
  });
  const [materielsDemandes, setMaterielsDemandes] = useState(emptyMaterialEventSelection);
  const [quantitesDemandees, setQuantitesDemandees] = useState(emptyMaterialEventQuantities);
  const [selectedDocuments, setSelectedDocuments] = useState<number[]>([]);
  const [selectedSalles, setSelectedSalles] = useState<string[]>([]);
  const [originalReservationPayload, setOriginalReservationPayload] = useState<Record<string, any>>({});
  const [legacyReservationDetected, setLegacyReservationDetected] = useState(false);
  const [initialized, setInitialized] = useState(false);
  const [isSubmittingAfterSave, setIsSubmittingAfterSave] = useState(false);

  // Initialize form with existing request data
  useEffect(() => {
    if (request && !initialized) {
      let parsedFormData: any = {};
      try {
        parsedFormData = request.formData ? JSON.parse(request.formData) : {};
      } catch {
        parsedFormData = {};
      }

      const reservationSallePayload = request.type === 'demande_salle'
        ? parseReservationSallePayload(request.formData)
        : null;

      setFormData({
        titre: request.titre || '',
        description: request.description || reservationSallePayload?.formData.motifReservation || '',
        montantDemande: request.montantDemande ? String(request.montantDemande / 100) : '',
        objetProjet: parsedFormData.objetProjet || '',
        dateDebut: parsedFormData.dateDebut || '',
        dateFin: parsedFormData.dateFin || '',
        publicVise: parsedFormData.publicVise || '',
        commune: parsedFormData.commune || '',
        direction: parsedFormData.direction || '',
        service: parsedFormData.service || '',
        demandeurNomPrenom: parsedFormData.demandeurNomPrenom || '',
        dateDemande: parsedFormData.dateDemande || '',
        dateDebutManifestation: parsedFormData.dateDebutManifestation || parsedFormData.dateManifestation || '',
        dateFinManifestation: parsedFormData.dateFinManifestation || parsedFormData.dateManifestation || '',
        motifDemande: parsedFormData.motifDemande || '',
        datePriseEnCharge: parsedFormData.datePriseEnCharge || '',
        dateRestitution: parsedFormData.dateRestitution || '',
        autreMaterielPrecisions: parsedFormData.autreMaterielPrecisions || '',
        dgsSignataire: parsedFormData.dgsSignataire || '',
        motifReservation: reservationSallePayload?.formData.motifReservation || '',
        dateReservation: reservationSallePayload?.formData.dateReservation || '',
        dateFinReservation: reservationSallePayload?.formData.dateFinReservation || '',
        heureDebut: reservationSallePayload?.formData.heureDebut || '',
        heureFin: reservationSallePayload?.formData.heureFin || '',
        useDetailedSchedule: reservationSallePayload?.formData.useDetailedSchedule || false,
        horairesParJour: reservationSallePayload?.formData.horairesParJour || [],
        typeUsage: reservationSallePayload?.formData.typeUsage || 'conventionne',
        frequence: reservationSallePayload?.formData.frequence || 'journee',
        nombreParticipants: reservationSallePayload?.formData.nombreParticipants || parsedFormData.nombreParticipants || '',
        besoinsComplementaires: reservationSallePayload?.formData.besoinsComplementaires || '',
        materielNecessaire: reservationSallePayload?.formData.materielNecessaire || '',
        observations: reservationSallePayload?.formData.observations || '',
      });

      if (reservationSallePayload) {
        setSelectedSalles(reservationSallePayload.selectedSalles);
        setOriginalReservationPayload(reservationSallePayload.originalData);
        setLegacyReservationDetected(reservationSallePayload.legacyDetected);
      }

      if (request.type === 'demande_materiel_evenementiel') {
        setMaterielsDemandes({
          ...emptyMaterialEventSelection(),
          ...(parsedFormData.materielsDemandes || {}),
        });
        setQuantitesDemandees({
          ...emptyMaterialEventQuantities(),
          ...(parsedFormData.quantitesDemandees || {}),
        });
      }

      // Parse existing documents
      if (request.documentsJoints) {
        try {
          const docs = JSON.parse(request.documentsJoints);
          if (Array.isArray(docs)) {
            setSelectedDocuments(docs);
          }
        } catch {
          // ignore
        }
      }

      setInitialized(true);
    }
  }, [request, initialized]);

  useEffect(() => {
    if (request?.type !== 'demande_materiel_evenementiel') {
      return;
    }

    if (!formData.dateFinManifestation) {
      return;
    }

    const nextRestitution = (() => {
      const date = new Date(formData.dateFinManifestation);
      if (Number.isNaN(date.getTime())) return "";
      date.setDate(date.getDate() + restitutionGraceDays);
      return date.toISOString().split("T")[0];
    })();

    if (formData.dateRestitution === nextRestitution) {
      return;
    }

    setFormData((prev) => ({
      ...prev,
      dateRestitution: nextRestitution,
    }));
  }, [request?.type, formData.dateFinManifestation, formData.dateRestitution, restitutionGraceDays]);

  const updateMutation = trpc.request.update.useMutation({
    onSuccess: () => {
      if (!isSubmittingAfterSave) {
        toast.success('Demande mise à jour avec succès');
      }
      utils.request.getById.invalidate({ id: requestId });
      utils.request.getMyRequests.invalidate();
    },
    onError: (error) => {
      toast.error(error.message || 'Erreur lors de la mise à jour');
    },
  });

  const submitMutation = trpc.request.submit.useMutation({
    onError: (error) => {
      toast.error(error.message || 'Erreur lors de la soumission');
    },
  });

  const validateBeforeSave = () => {
    if (!request) {
      return false;
    }

    if (!formData.titre) {
      toast.error('Le titre est obligatoire');
      return false;
    }

    if (request.type === 'demande_salle') {
      const validationError = validateReservationSalleFormInput(
        {
          motifReservation: formData.motifReservation,
          dateReservation: formData.dateReservation,
          dateFinReservation: formData.dateFinReservation,
          heureDebut: formData.heureDebut,
          heureFin: formData.heureFin,
          useDetailedSchedule: formData.useDetailedSchedule,
          horairesParJour: formData.horairesParJour,
          typeUsage: formData.typeUsage,
          frequence: formData.frequence,
          nombreParticipants: formData.nombreParticipants,
          besoinsComplementaires: formData.besoinsComplementaires,
          materielNecessaire: formData.materielNecessaire,
          observations: formData.observations,
        },
        selectedSalles
      );

      if (validationError) {
        toast.error(validationError);
        return false;
      }
    }

    if (request.type === 'demande_materiel_evenementiel') {
      if (!formData.direction || !formData.service || !formData.dateDebutManifestation || !formData.dateFinManifestation || !formData.motifDemande) {
        toast.error('Veuillez remplir les champs obligatoires');
        return false;
      }
      if (formData.dateFinManifestation < formData.dateDebutManifestation) {
        toast.error('La date de fin de manifestation doit être postérieure ou égale à la date de début');
        return false;
      }
      const selectedMaterialCount = Object.values(materielsDemandes).filter(Boolean).length;
      if (selectedMaterialCount === 0) {
        toast.error('Veuillez sélectionner au moins un matériel');
        return false;
      }
      const invalidQuantity = materialEventItems.some(item => materielsDemandes[item.key] && !quantitesDemandees[item.key]);
      if (invalidQuantity) {
        toast.error('Veuillez renseigner la quantité pour chaque matériel sélectionné');
        return false;
      }
      if (materielsDemandes.autres && !formData.autreMaterielPrecisions.trim()) {
        toast.error('Veuillez préciser le matériel demandé dans le champ "Autres"');
        return false;
      }
      if (formData.dateRestitution) {
        const maxReturnDate = new Date(formData.dateFinManifestation);
        maxReturnDate.setDate(maxReturnDate.getDate() + restitutionGraceDays);
        const maxReturnDateStr = maxReturnDate.toISOString().split("T")[0];
        if (formData.dateRestitution > maxReturnDateStr) {
          toast.error(`La date de restitution ne peut pas dépasser ${restitutionGraceDays} jour(s) après la fin de la manifestation`);
          return false;
        }
      }
    }

    return true;
  };

  const buildRequestUpdatePayload = () => {
    if (!request) {
      return null;
    }

    const formDataJson = request.type === 'demande_salle'
      ? JSON.stringify(
          buildReservationSallePayload({
            existingData: originalReservationPayload,
            association,
            formData: {
              motifReservation: formData.motifReservation,
              dateReservation: formData.dateReservation,
              dateFinReservation: formData.dateFinReservation,
              heureDebut: formData.heureDebut,
              heureFin: formData.heureFin,
              useDetailedSchedule: formData.useDetailedSchedule,
              horairesParJour: formData.horairesParJour,
              typeUsage: formData.typeUsage,
              frequence: formData.frequence,
              nombreParticipants: formData.nombreParticipants,
              besoinsComplementaires: formData.besoinsComplementaires,
              materielNecessaire: formData.materielNecessaire,
              observations: formData.observations,
            },
            selectedSalles,
          })
        )
      : request.type === 'demande_materiel_evenementiel'
        ? JSON.stringify({
            formulaireType: "demande_materiel_evenementiel",
            commune: formData.commune,
            direction: formData.direction,
            service: formData.service,
            demandeurNomPrenom: formData.demandeurNomPrenom,
            dateDemande: getTodayDateString(),
            dateManifestation: formData.dateDebutManifestation,
            dateDebutManifestation: formData.dateDebutManifestation,
            dateFinManifestation: formData.dateFinManifestation,
            motifDemande: formData.motifDemande,
            datePriseEnCharge: formData.datePriseEnCharge,
            dateRestitution: formData.dateRestitution,
            dgsSignataire: formData.dgsSignataire,
            autreMaterielPrecisions: formData.autreMaterielPrecisions,
            materielsDemandes,
            quantitesDemandees,
            nomAssociation: association?.nomAssociation || '',
            adresseAssociation: association?.adresse ? `${association.adresse}, ${association.codePostal || ""} ${association.ville || ""}`.trim() : "",
            communeSiege: association?.ville || "",
            representantLegal: association?.nomRepresentant || "",
            telephoneAssociation: association?.telephone || "",
            emailAssociation: association?.emailContact || "",
            emailDestinataire: "sport-culture@ccds-guyane.fr",
            destinataire: "Direction des Services aux Usagers (DSU)",
          })
        : JSON.stringify({
            ...formData,
            associationInfo: association ? {
              nom: association.nomAssociation,
              siret: association.siret,
              adresse: `${association.adresse}, ${association.codePostal} ${association.ville}`,
              representant: association.nomRepresentant,
            } : null,
          });

    return {
      id: requestId,
      titre: formData.titre,
      description: request.type === 'demande_salle' ? formData.motifReservation : formData.description,
      formData: formDataJson,
      montantDemande: formData.montantDemande ? parseInt(formData.montantDemande) * 100 : undefined,
      documentsJoints: selectedDocuments.length > 0 ? selectedDocuments : undefined,
    };
  };

  const handleSave = () => {
    if (!validateBeforeSave()) {
      return;
    }

    const payload = buildRequestUpdatePayload();
    if (!payload) {
      return;
    }

    updateMutation.mutate(payload);
  };

  const handleSaveAndSubmit = async () => {
    if (!request) {
      return;
    }

    if (request.status !== 'brouillon' && request.status !== 'information_complementaire') {
      handleSave();
      return;
    }

    if (!validateBeforeSave()) {
      return;
    }

    const payload = buildRequestUpdatePayload();
    if (!payload) {
      return;
    }

    try {
      setIsSubmittingAfterSave(true);
      await updateMutation.mutateAsync(payload);
      await submitMutation.mutateAsync({ id: requestId });
      toast.success('Demande soumise avec succès !');
      utils.request.getById.invalidate({ id: requestId });
      utils.request.getMyRequests.invalidate();
      setLocation('/dashboard');
    } finally {
      setIsSubmittingAfterSave(false);
    }
  };

  const handleToggleMaterial = (key: MaterialEventItemKey, checked: boolean) => {
    setMaterielsDemandes(prev => ({ ...prev, [key]: checked }));
    if (!checked) {
      setQuantitesDemandees(prev => ({ ...prev, [key]: "" }));
      if (key === "autres") {
        setFormData(prev => ({ ...prev, autreMaterielPrecisions: "" }));
      }
    }
  };

  const deleteMutation = trpc.request.delete.useMutation({
    onSuccess: () => {
      toast.success('Demande supprimée avec succès');
      setLocation('/dashboard/requests');
    },
    onError: (error) => {
      toast.error(error.message || 'Erreur lors de la suppression');
    },
  });

  const canEdit = request && (request.status === 'brouillon' || request.status === 'information_complementaire');
  const isInfoRequest = request?.status === 'information_complementaire';
  const canDelete = request && request.status !== 'validee' && request.status !== 'refusee' && request.status !== 'annulee';
  const canSubmitFromEdit = request?.status === 'brouillon' || request?.status === 'information_complementaire';
  const reservationDates = useMemo(
    () => listReservationDates(formData.dateReservation, formData.dateFinReservation),
    [formData.dateReservation, formData.dateFinReservation]
  );
  const canUseDetailedSchedule = reservationDates.length > 1;

  useEffect(() => {
    if (request?.type !== 'demande_salle') {
      return;
    }

    setFormData((prev) => {
      if (!prev.useDetailedSchedule) {
        return prev.horairesParJour.length > 0 ? { ...prev, horairesParJour: [] } : prev;
      }

      const nextSlots = syncReservationSalleDailySlots(
        prev.dateReservation,
        prev.dateFinReservation,
        prev.horairesParJour,
        prev.heureDebut,
        prev.heureFin
      );

      if (JSON.stringify(nextSlots) === JSON.stringify(prev.horairesParJour)) {
        return prev;
      }

      return {
        ...prev,
        horairesParJour: nextSlots,
      };
    });
  }, [
    request?.type,
    formData.useDetailedSchedule,
    formData.dateReservation,
    formData.dateFinReservation,
    formData.heureDebut,
    formData.heureFin,
  ]);

  if (requestLoading) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <Loader2 className="h-8 w-8 animate-spin text-primary" />
      </div>
    );
  }

  const salleWorkflowLockState = request?.type === "demande_salle"
    ? getSalleWorkflowLockState(request.formData)
    : { quoteStatus: null, directorStatus: null, finalNotificationSentAt: null };
  const editingLockedForSalleResponse = salleWorkflowLockState.quoteStatus === "en_attente_association";
  const editingLockedForSalleFinalization =
    salleWorkflowLockState.directorStatus === "signee" && !salleWorkflowLockState.finalNotificationSentAt;

  if (request && editingLockedForSalleResponse) {
    return (
      <div className="min-h-screen bg-muted/30">
        <header className="border-b border-border bg-white sticky top-0 z-10">
          <div className="container py-4">
            <div className="flex items-center gap-4">
              <Link href={`/dashboard/requests/${requestId}`}>
                <Button variant="ghost" size="icon">
                  <ArrowLeft className="h-5 w-5" />
                </Button>
              </Link>
              <h1 className="text-xl font-bold">Édition indisponible</h1>
            </div>
          </div>
        </header>
        <main className="container py-8">
          <Card className="max-w-2xl mx-auto">
            <CardHeader>
              <CardTitle>Cette demande attend votre réponse</CardTitle>
              <CardDescription>
                Le devis et la décision administrative ont été envoyés. Vous ne pouvez plus modifier la demande tant que vous n’avez pas répondu.
              </CardDescription>
            </CardHeader>
            <CardContent className="flex flex-wrap gap-3">
              <Link href={`/dashboard/requests/${requestId}`}>
                <Button>
                  <FileText className="mr-2 h-4 w-4" />
                  Retour à la demande
                </Button>
              </Link>
            </CardContent>
          </Card>
        </main>
      </div>
    );
  }

  if (request && editingLockedForSalleFinalization) {
    return (
      <div className="min-h-screen bg-muted/30">
        <header className="border-b border-border bg-white sticky top-0 z-10">
          <div className="container py-4">
            <div className="flex items-center gap-4">
              <Link href={`/dashboard/requests/${requestId}`}>
                <Button variant="ghost" size="icon">
                  <ArrowLeft className="h-5 w-5" />
                </Button>
              </Link>
              <h1 className="text-xl font-bold">Édition indisponible</h1>
            </div>
          </div>
        </header>
        <main className="container py-8">
          <Card className="max-w-2xl mx-auto">
            <CardHeader>
              <CardTitle>Cette demande est prête pour l’envoi final</CardTitle>
              <CardDescription>
                Le dossier a déjà été signé par la Direction. À ce stade, la secrétaire ne peut plus modifier la demande :
                elle doit uniquement vérifier les documents générés puis envoyer la confirmation finale à l’association.
              </CardDescription>
            </CardHeader>
            <CardContent className="flex flex-wrap gap-3">
              <Link href={`/dashboard/requests/${requestId}`}>
                <Button>
                  <FileText className="mr-2 h-4 w-4" />
                  Retour à la demande
                </Button>
              </Link>
            </CardContent>
          </Card>
        </main>
      </div>
    );
  }

  if (!request) {
    return (
      <div className="min-h-screen bg-muted/30">
        <header className="border-b border-border bg-white sticky top-0 z-10">
          <div className="container py-4">
            <div className="flex items-center gap-4">
              <Link href="/dashboard/requests">
                <Button variant="ghost" size="icon">
                  <ArrowLeft className="h-5 w-5" />
                </Button>
              </Link>
              <h1 className="text-xl font-bold">Demande introuvable</h1>
            </div>
          </div>
        </header>
        <main className="container py-8">
          <Card className="max-w-md mx-auto">
            <CardContent className="py-12 text-center">
              <p className="text-muted-foreground">Cette demande n'existe pas ou vous n'y avez pas accès.</p>
              <Link href="/dashboard/requests">
                <Button className="mt-4">Retour aux demandes</Button>
              </Link>
            </CardContent>
          </Card>
        </main>
      </div>
    );
  }

  if (!canEdit) {
    return (
      <div className="min-h-screen bg-muted/30">
        <header className="border-b border-border bg-white sticky top-0 z-10">
          <div className="container py-4">
            <div className="flex items-center gap-4">
              <Link href={`/dashboard/requests/${requestId}`}>
                <Button variant="ghost" size="icon">
                  <ArrowLeft className="h-5 w-5" />
                </Button>
              </Link>
              <h1 className="text-xl font-bold">Modification impossible</h1>
            </div>
          </div>
        </header>
        <main className="container py-8">
          <Card className="max-w-md mx-auto">
            <CardContent className="py-12 text-center">
              <p className="text-muted-foreground">Cette demande ne peut plus être modifiée dans son état actuel.</p>
              <Link href={`/dashboard/requests/${requestId}`}>
                <Button className="mt-4">Retour à la demande</Button>
              </Link>
            </CardContent>
          </Card>
        </main>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-muted/30">
      {/* Header */}
      <header className="border-b border-border bg-white sticky top-0 z-10">
        <div className="container py-4">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-4">
              <Link href={`/dashboard/requests/${requestId}`}>
                <Button variant="ghost" size="icon">
                  <ArrowLeft className="h-5 w-5" />
                </Button>
              </Link>
              <div>
                <h1 className="text-xl font-bold">
                  Éditer la demande
                </h1>
                <p className="text-sm text-muted-foreground">
                  {requestTypeLabels[request.type] || request.type}
                </p>
              </div>
            </div>
            <div className="flex items-center gap-2">
              <Button 
                variant="outline" 
                onClick={handleSave}
                disabled={updateMutation.isPending}
              >
                {updateMutation.isPending ? (
                  <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                ) : (
                  <Save className="mr-2 h-4 w-4" />
                )}
                Enregistrer
              </Button>
              {canSubmitFromEdit && (
                <Button 
                  onClick={handleSaveAndSubmit}
                  disabled={updateMutation.isPending || submitMutation.isPending}
                >
                  {submitMutation.isPending ? (
                    <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                  ) : (
                    <Send className="mr-2 h-4 w-4" />
                  )}
                  {isInfoRequest ? 'Renvoyer la demande' : 'Soumettre la demande'}
                </Button>
              )}
              {canDelete && (
                <AlertDialog>
                  <AlertDialogTrigger asChild>
                    <Button variant="destructive" size="default">
                      <Trash2 className="mr-2 h-4 w-4" />
                      Annuler la demande
                    </Button>
                  </AlertDialogTrigger>
                  <AlertDialogContent>
                    <AlertDialogHeader>
                      <AlertDialogTitle>Annuler cette demande ?</AlertDialogTitle>
                      <AlertDialogDescription>
                        Cette action est irréversible. La demande « {request?.titre} » sera définitivement supprimée.
                      </AlertDialogDescription>
                    </AlertDialogHeader>
                    <AlertDialogFooter>
                      <AlertDialogCancel>Retour</AlertDialogCancel>
                      <AlertDialogAction
                        onClick={() => deleteMutation.mutate({ id: requestId })}
                        className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
                      >
                        {deleteMutation.isPending ? (
                          <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                        ) : (
                          <Trash2 className="mr-2 h-4 w-4" />
                        )}
                        Supprimer définitivement
                      </AlertDialogAction>
                    </AlertDialogFooter>
                  </AlertDialogContent>
                </AlertDialog>
              )}
            </div>
          </div>
        </div>
      </header>

      <main className="container py-8">
        <div className="max-w-2xl mx-auto space-y-6">
          {/* Info banner for information_complementaire */}
          {isInfoRequest && request.commentaireAdmin && (
            <Card className="border-orange-200 bg-orange-50">
              <CardContent className="py-4">
                <div className="flex items-start gap-3">
                  <div className="w-8 h-8 rounded-full bg-orange-100 flex items-center justify-center flex-shrink-0 mt-0.5">
                    <FileText className="h-4 w-4 text-orange-600" />
                  </div>
                  <div>
                    <p className="font-medium text-orange-800">Information complémentaire demandée</p>
                    <p className="text-sm text-orange-700 mt-1">{request.commentaireAdmin}</p>
                    <p className="text-xs text-orange-600 mt-2">
                      Veuillez compléter votre demande et la renvoyer.
                    </p>
                  </div>
                </div>
              </CardContent>
            </Card>
          )}

          {/* Form fields */}
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <FileText className="h-5 w-5 text-primary" />
                Informations de la demande
              </CardTitle>
              <CardDescription>
                Modifiez les informations de votre demande
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="space-y-2">
                <Label htmlFor="titre">Titre de la demande *</Label>
                <Input
                  id="titre"
                  value={formData.titre}
                  onChange={(e) => setFormData(prev => ({ ...prev, titre: e.target.value }))}
                  placeholder="Ex: Subvention pour le projet culturel 2025"
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="description">Description</Label>
                <Textarea
                  id="description"
                  value={formData.description}
                  onChange={(e) => setFormData(prev => ({ ...prev, description: e.target.value }))}
                  placeholder="Décrivez votre demande en détail..."
                  rows={4}
                />
              </div>

              {/* Subvention specific fields */}
              {(request.type === 'subvention_fonctionnement' || request.type === 'subvention_projet') && (
                <>
                  <div className="space-y-2">
                    <Label htmlFor="montantDemande">Montant demandé (€)</Label>
                    <Input
                      id="montantDemande"
                      type="number"
                      value={formData.montantDemande}
                      onChange={(e) => setFormData(prev => ({ ...prev, montantDemande: e.target.value }))}
                      placeholder="5000"
                    />
                  </div>

                  {request.type === 'subvention_projet' && (
                    <>
                      <div className="space-y-2">
                        <Label htmlFor="objetProjet">Objet du projet</Label>
                        <Textarea
                          id="objetProjet"
                          value={formData.objetProjet}
                          onChange={(e) => setFormData(prev => ({ ...prev, objetProjet: e.target.value }))}
                          placeholder="Décrivez l'objet et les objectifs du projet..."
                          rows={3}
                        />
                      </div>
                      <div className="grid gap-4 md:grid-cols-2">
                        <div className="space-y-2">
                          <Label htmlFor="dateDebut">Date de début</Label>
                          <Input
                            id="dateDebut"
                            type="date"
                            value={formData.dateDebut}
                            onChange={(e) => setFormData(prev => ({ ...prev, dateDebut: e.target.value }))}
                          />
                        </div>
                        <div className="space-y-2">
                          <Label htmlFor="dateFin">Date de fin</Label>
                          <Input
                            id="dateFin"
                            type="date"
                            value={formData.dateFin}
                            onChange={(e) => setFormData(prev => ({ ...prev, dateFin: e.target.value }))}
                          />
                        </div>
                      </div>
                      <div className="space-y-2">
                        <Label htmlFor="publicVise">Public visé</Label>
                        <Input
                          id="publicVise"
                          value={formData.publicVise}
                          onChange={(e) => setFormData(prev => ({ ...prev, publicVise: e.target.value }))}
                          placeholder="Ex: Jeunes de 12 à 25 ans"
                        />
                      </div>
                    </>
                  )}
                </>
              )}

              {/* Salle specific fields */}
              {request.type === 'demande_salle' && (
                <>
                  <Separator />
                  <div>
                    <div className="mb-3 flex items-center gap-2">
                      <CalendarDays className="h-5 w-5 text-primary" />
                      <h3 className="font-medium">Locaux sollicités</h3>
                    </div>
                    <div className="grid gap-3 md:grid-cols-2">
                      {sallesMJS.map((salle) => {
                        const selected = selectedSalles.includes(salle.id);
                        return (
                          <button
                            key={salle.id}
                            type="button"
                            className={`rounded-lg border p-4 text-left transition-colors ${
                              selected ? 'border-primary bg-primary/5' : 'hover:border-primary/40'
                            }`}
                            onClick={() => setSelectedSalles((prev) =>
                              prev.includes(salle.id)
                                ? prev.filter((id) => id !== salle.id)
                                : [...prev, salle.id]
                            )}
                          >
                            <div className="flex items-start justify-between gap-3">
                              <div>
                                <div className="font-medium">{salle.nom}</div>
                                <div className="text-sm text-muted-foreground">{salle.description}</div>
                                <div className="mt-1 text-xs text-muted-foreground">{salle.capacite}</div>
                              </div>
                              {selected ? <CheckCircle className="h-5 w-5 text-primary shrink-0" /> : null}
                            </div>
                          </button>
                        );
                      })}
                    </div>
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor="motifReservation">Motif de la réservation *</Label>
                    <Textarea
                      id="motifReservation"
                      value={formData.motifReservation}
                      onChange={(e) => setFormData(prev => ({ ...prev, motifReservation: e.target.value, description: e.target.value }))}
                      placeholder="Décrivez le motif de votre réservation..."
                      rows={3}
                    />
                  </div>

                  <div className="grid gap-4 md:grid-cols-2">
                    <div className="space-y-2">
                      <Label htmlFor="dateReservation">Date de début *</Label>
                      <Input
                        id="dateReservation"
                        type="date"
                        value={formData.dateReservation}
                        onChange={(e) => setFormData(prev => {
                          const nextStart = e.target.value;
                          const nextEnd = !prev.dateFinReservation || prev.dateFinReservation < nextStart
                            ? nextStart
                            : prev.dateFinReservation;
                          return {
                            ...prev,
                            dateReservation: nextStart,
                            dateFinReservation: nextEnd,
                          };
                        })}
                      />
                    </div>
                    <div className="space-y-2">
                      <Label htmlFor="dateFinReservation">Date de fin *</Label>
                      <Input
                        id="dateFinReservation"
                        type="date"
                        value={formData.dateFinReservation}
                        min={formData.dateReservation || undefined}
                        onChange={(e) => setFormData(prev => ({ ...prev, dateFinReservation: e.target.value }))}
                      />
                    </div>
                  </div>
                  <div className="grid gap-4 md:grid-cols-2">
                    <div className="space-y-2">
                      <Label htmlFor="heureDebut">Heure de début commune *</Label>
                      <Input
                        id="heureDebut"
                        type="time"
                        value={formData.heureDebut}
                        onChange={(e) => setFormData(prev => ({ ...prev, heureDebut: e.target.value }))}
                      />
                    </div>
                    <div className="space-y-2">
                      <Label htmlFor="heureFin">Heure de fin commune *</Label>
                      <Input
                        id="heureFin"
                        type="time"
                        value={formData.heureFin}
                        onChange={(e) => setFormData(prev => ({ ...prev, heureFin: e.target.value }))}
                      />
                    </div>
                  </div>
                  {canUseDetailedSchedule ? (
                    <div className="rounded-lg border border-primary/20 bg-primary/5 px-4 py-4 space-y-4">
                      <div className="flex items-start gap-3">
                        <Checkbox
                          id="edit-useDetailedSchedule"
                          checked={formData.useDetailedSchedule}
                          onCheckedChange={(checked) =>
                            setFormData((prev) => ({
                              ...prev,
                              useDetailedSchedule: Boolean(checked),
                              horairesParJour: checked
                                ? syncReservationSalleDailySlots(
                                    prev.dateReservation,
                                    prev.dateFinReservation,
                                    prev.horairesParJour,
                                    prev.heureDebut,
                                    prev.heureFin
                                  )
                                : [],
                            }))
                          }
                        />
                        <div className="space-y-1">
                          <Label htmlFor="edit-useDetailedSchedule" className="cursor-pointer">
                            Les horaires changent selon les jours
                          </Label>
                          <p className="text-xs text-muted-foreground">
                            Active ce mode seulement si le même créneau ne s'applique pas à toute la période.
                          </p>
                        </div>
                      </div>

                      {formData.useDetailedSchedule ? (
                        <div className="space-y-3">
                          <div className="flex justify-end">
                            <Button
                              type="button"
                              variant="outline"
                              size="sm"
                              onClick={() =>
                                setFormData((prev) => ({
                                  ...prev,
                                  horairesParJour: prev.horairesParJour.map((slot) => ({
                                    ...slot,
                                    heureDebut: prev.heureDebut,
                                    heureFin: prev.heureFin,
                                  })),
                                }))
                              }
                            >
                              Appliquer le créneau commun à tous les jours
                            </Button>
                          </div>
                          {formData.horairesParJour.map((slot, index) => (
                            <div key={slot.date} className="rounded-lg border bg-background p-3">
                              <div className="grid gap-3 md:grid-cols-[1fr,160px,160px] md:items-end">
                                <div>
                                  <Label>Date</Label>
                                  <div className="mt-2 rounded-md border bg-muted/40 px-3 py-2 text-sm font-medium">
                                    {new Date(`${slot.date}T12:00:00`).toLocaleDateString('fr-FR', {
                                      weekday: 'long',
                                      day: 'numeric',
                                      month: 'long',
                                      year: 'numeric',
                                    })}
                                  </div>
                                </div>
                                <div className="space-y-2">
                                  <Label htmlFor={`edit-slot-start-${slot.date}`}>Début</Label>
                                  <Input
                                    id={`edit-slot-start-${slot.date}`}
                                    type="time"
                                    value={slot.heureDebut}
                                    onChange={(e) =>
                                      setFormData((prev) => ({
                                        ...prev,
                                        horairesParJour: prev.horairesParJour.map((current, currentIndex) =>
                                          currentIndex === index
                                            ? { ...current, heureDebut: e.target.value }
                                            : current
                                        ),
                                      }))
                                    }
                                  />
                                </div>
                                <div className="space-y-2">
                                  <Label htmlFor={`edit-slot-end-${slot.date}`}>Fin</Label>
                                  <Input
                                    id={`edit-slot-end-${slot.date}`}
                                    type="time"
                                    value={slot.heureFin}
                                    onChange={(e) =>
                                      setFormData((prev) => ({
                                        ...prev,
                                        horairesParJour: prev.horairesParJour.map((current, currentIndex) =>
                                          currentIndex === index
                                            ? { ...current, heureFin: e.target.value }
                                            : current
                                        ),
                                      }))
                                    }
                                  />
                                </div>
                              </div>
                            </div>
                          ))}
                        </div>
                      ) : null}
                    </div>
                  ) : null}
                  <div className="space-y-2">
                    <Label htmlFor="nombreParticipants">Nombre de participants prévu *</Label>
                    <Input
                      id="nombreParticipants"
                      type="number"
                      value={formData.nombreParticipants}
                      onChange={(e) => setFormData(prev => ({ ...prev, nombreParticipants: e.target.value }))}
                      placeholder="50"
                    />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="materielNecessaire">Matériel nécessaire</Label>
                    <Textarea
                      id="materielNecessaire"
                      value={formData.materielNecessaire}
                      onChange={(e) => setFormData(prev => ({ ...prev, materielNecessaire: e.target.value }))}
                      placeholder="Ex: Tables, chaises, vidéoprojecteur..."
                      rows={2}
                    />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="observations">Observations complémentaires</Label>
                    <Textarea
                      id="observations"
                      value={formData.observations}
                      onChange={(e) => setFormData(prev => ({ ...prev, observations: e.target.value }))}
                      placeholder="Toute information complémentaire utile..."
                      rows={2}
                    />
                  </div>
                  <div className="rounded-lg border border-primary/20 bg-primary/5 px-4 py-3 text-sm text-primary">
                    La réservation peut porter sur plusieurs jours. Utilise un créneau commun si l'horaire reste le même, ou active les horaires détaillés si chaque journée diffère.
                  </div>
                  {legacyReservationDetected ? (
                    <div className="rounded-lg border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-800">
                      Cette demande a été enregistrée avec un ancien format. Vérifie les salles, la période et les horaires avant d'enregistrer pour la remettre au propre.
                    </div>
                  ) : null}
                </>
              )}

              {request.type === 'demande_materiel_evenementiel' && (
                <>
                  <Separator />
                  <div className="grid gap-4 md:grid-cols-2">
                    <div className="space-y-2">
                      <Label htmlFor="commune">Commune</Label>
                      <Input
                        id="commune"
                        value={formData.commune}
                        onChange={(e) => setFormData(prev => ({ ...prev, commune: e.target.value }))}
                      />
                    </div>
                    <div className="space-y-2">
                      <Label htmlFor="direction">Direction *</Label>
                      <Input
                        id="direction"
                        value={formData.direction}
                        onChange={(e) => setFormData(prev => ({ ...prev, direction: e.target.value }))}
                      />
                    </div>
                    <div className="space-y-2">
                      <Label htmlFor="service">Service *</Label>
                      <Input
                        id="service"
                        value={formData.service}
                        onChange={(e) => setFormData(prev => ({ ...prev, service: e.target.value }))}
                      />
                    </div>
                    <div className="space-y-2">
                      <Label htmlFor="demandeurNomPrenom">Nom et prénom du demandeur</Label>
                      <Input
                        id="demandeurNomPrenom"
                        value={formData.demandeurNomPrenom}
                        onChange={(e) => setFormData(prev => ({ ...prev, demandeurNomPrenom: e.target.value }))}
                      />
                    </div>
                  </div>

                  <div className="space-y-4">
                    <div className="flex items-center gap-2">
                      <CheckCircle className="h-5 w-5 text-primary" />
                      <h3 className="font-medium">Matériel demandé</h3>
                    </div>
                    <div className="grid gap-4 md:grid-cols-2">
                      {materialEventItems.map((item) => (
                        <div key={item.key} className="rounded-lg border p-4 space-y-3">
                          <div className="flex items-center gap-3">
                            <Checkbox
                              checked={materielsDemandes[item.key]}
                              onCheckedChange={(checked) => handleToggleMaterial(item.key, Boolean(checked))}
                            />
                            <span className="font-medium">{item.label}</span>
                          </div>
                          <div className="space-y-2">
                            <Label htmlFor={`qty-${item.key}`}>Quantité demandée</Label>
                            <Input
                              id={`qty-${item.key}`}
                              value={quantitesDemandees[item.key]}
                              onChange={(e) => setQuantitesDemandees(prev => ({ ...prev, [item.key]: e.target.value }))}
                              disabled={!materielsDemandes[item.key]}
                              inputMode="numeric"
                              placeholder="..."
                            />
                          </div>
                          {item.key === "autres" && materielsDemandes.autres ? (
                            <div className="space-y-2">
                              <Label htmlFor="autreMaterielPrecisions">Précisions sur le matériel</Label>
                              <Textarea
                                id="autreMaterielPrecisions"
                                value={formData.autreMaterielPrecisions}
                                onChange={(e) => setFormData(prev => ({ ...prev, autreMaterielPrecisions: e.target.value }))}
                                rows={3}
                              />
                            </div>
                          ) : null}
                        </div>
                      ))}
                    </div>
                  </div>

                  <div className="grid gap-4 md:grid-cols-2">
                    <div className="space-y-2">
                      <Label htmlFor="dateDemande">Date de la demande</Label>
                      <div className="rounded-md border bg-muted/40 px-3 py-2 text-sm text-muted-foreground">
                        Enregistrée automatiquement le jour de l'envoi.
                      </div>
                    </div>
                    <div className="space-y-2">
                      <Label htmlFor="dateDebutManifestation">Début de la manifestation *</Label>
                      <Input
                        id="dateDebutManifestation"
                        type="date"
                        value={formData.dateDebutManifestation}
                        onChange={(e) => setFormData(prev => {
                          const nextStart = e.target.value;
                          const currentEnd = prev.dateFinManifestation || nextStart;
                          const nextEnd = currentEnd && currentEnd < nextStart ? nextStart : currentEnd;
                          return {
                            ...prev,
                            dateDebutManifestation: nextStart,
                            dateFinManifestation: nextEnd,
                          };
                        })}
                      />
                    </div>
                    <div className="space-y-2">
                      <Label htmlFor="dateFinManifestation">Fin de la manifestation *</Label>
                      <Input
                        id="dateFinManifestation"
                        type="date"
                        value={formData.dateFinManifestation}
                        min={formData.dateDebutManifestation || undefined}
                        onChange={(e) => setFormData(prev => ({ ...prev, dateFinManifestation: e.target.value }))}
                      />
                    </div>
                    <div className="space-y-2">
                      <Label htmlFor="datePriseEnCharge">Date de prise en charge</Label>
                      <div className="rounded-md border bg-muted/40 px-3 py-2 text-sm text-muted-foreground">
                        Cette date est renseignée par l'administration.
                      </div>
                    </div>
                    <div className="space-y-2">
                      <Label htmlFor="dateRestitution">Date de restitution</Label>
                      <Input
                        id="dateRestitution"
                        type="date"
                        value={formData.dateRestitution}
                        readOnly
                      />
                    </div>
                    <div className="space-y-2">
                      <Label htmlFor="dgsSignataire">Nom du signataire</Label>
                      <Input
                        id="dgsSignataire"
                        value={formData.dgsSignataire}
                        onChange={(e) => setFormData(prev => ({ ...prev, dgsSignataire: e.target.value }))}
                      />
                    </div>
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor="motifDemande">Motif de la demande *</Label>
                    <Textarea
                      id="motifDemande"
                      value={formData.motifDemande}
                      onChange={(e) => setFormData(prev => ({
                        ...prev,
                        motifDemande: e.target.value,
                        description: e.target.value,
                      }))}
                      rows={4}
                    />
                  </div>

                  <div className="rounded-lg border border-primary/20 bg-primary/5 px-4 py-3 text-sm text-primary">
                    Cette copie reste un vrai brouillon modifiable : tu peux ajuster les dates, le matériel, les quantités et les informations administratives avant de la soumettre.
                  </div>
                </>
              )}
            </CardContent>
          </Card>

          {/* Documents */}
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <Paperclip className="h-5 w-5 text-primary" />
                Documents joints
              </CardTitle>
              <CardDescription>
                Sélectionnez les documents à joindre à votre demande.
                <Link href="/dashboard/documents" className="text-primary hover:underline ml-1">
                  Gérer mes documents
                </Link>
              </CardDescription>
            </CardHeader>
            <CardContent>
              {documents && documents.length > 0 ? (
                <div className="space-y-3">
                  {documents.map((doc) => (
                    <div key={doc.id} className="flex items-center space-x-3 p-3 rounded-lg border hover:bg-muted/50 transition-colors">
                      <Checkbox
                        id={`doc-${doc.id}`}
                        checked={selectedDocuments.includes(doc.id)}
                        onCheckedChange={(checked) => {
                          if (checked) {
                            setSelectedDocuments(prev => [...prev, doc.id]);
                          } else {
                            setSelectedDocuments(prev => prev.filter(id => id !== doc.id));
                          }
                        }}
                      />
                      <Label htmlFor={`doc-${doc.id}`} className="flex-1 cursor-pointer">
                        <div className="font-medium">{doc.nom}</div>
                        <div className="text-sm text-muted-foreground">{doc.type}</div>
                      </Label>
                    </div>
                  ))}
                </div>
              ) : (
                <div className="text-center py-6 text-muted-foreground">
                  <Upload className="h-8 w-8 mx-auto mb-2 opacity-50" />
                  <p>Aucun document disponible.</p>
                  <Link href="/dashboard/documents" className="text-primary hover:underline text-sm">
                    Téléverser des documents
                  </Link>
                </div>
              )}
            </CardContent>
          </Card>

          {/* Association info */}
          {association && (
            <Card className="bg-muted/50">
              <CardHeader>
                <CardTitle className="flex items-center gap-2 text-base">
                  <Building2 className="h-5 w-5 text-primary" />
                  Informations de l'association (pré-remplies)
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="grid gap-2 text-sm">
                  <div className="flex justify-between">
                    <span className="text-muted-foreground">Nom:</span>
                    <span className="font-medium">{association.nomAssociation}</span>
                  </div>
                  {association.siret && (
                    <div className="flex justify-between">
                      <span className="text-muted-foreground">SIRET:</span>
                      <span className="font-medium">{association.siret}</span>
                    </div>
                  )}
                  {association.adresse && (
                    <div className="flex justify-between">
                      <span className="text-muted-foreground">Adresse:</span>
                      <span className="font-medium">
                        {association.adresse}, {association.codePostal} {association.ville}
                      </span>
                    </div>
                  )}
                  {association.nomRepresentant && (
                    <div className="flex justify-between">
                      <span className="text-muted-foreground">Représentant:</span>
                      <span className="font-medium">{association.nomRepresentant}</span>
                    </div>
                  )}
                </div>
              </CardContent>
            </Card>
          )}

          {/* Bottom action bar */}
          <div className="flex justify-between items-center pt-4 border-t">
            <Link href={`/dashboard/requests/${requestId}`}>
              <Button variant="outline">
                <ArrowLeft className="mr-2 h-4 w-4" />
                Retour
              </Button>
            </Link>
            <div className="flex items-center gap-2">
              <Button 
                variant="outline" 
                onClick={handleSave}
                disabled={updateMutation.isPending}
              >
                {updateMutation.isPending ? (
                  <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                ) : (
                  <Save className="mr-2 h-4 w-4" />
                )}
                Enregistrer
              </Button>
              {canSubmitFromEdit && (
              <Button 
                onClick={handleSaveAndSubmit}
                disabled={updateMutation.isPending || submitMutation.isPending}
              >
                {updateMutation.isPending || submitMutation.isPending ? (
                  <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                ) : (
                  <Send className="mr-2 h-4 w-4" />
                )}
                {isInfoRequest ? 'Renvoyer la demande' : 'Soumettre la demande'}
              </Button>
              )}
              {canDelete && (
                <AlertDialog>
                  <AlertDialogTrigger asChild>
                    <Button variant="destructive" size="default">
                      <Trash2 className="mr-2 h-4 w-4" />
                      Annuler la demande
                    </Button>
                  </AlertDialogTrigger>
                  <AlertDialogContent>
                    <AlertDialogHeader>
                      <AlertDialogTitle>Annuler cette demande ?</AlertDialogTitle>
                      <AlertDialogDescription>
                        Cette action est irréversible. La demande « {request?.titre} » sera définitivement supprimée.
                      </AlertDialogDescription>
                    </AlertDialogHeader>
                    <AlertDialogFooter>
                      <AlertDialogCancel>Retour</AlertDialogCancel>
                      <AlertDialogAction
                        onClick={() => deleteMutation.mutate({ id: requestId })}
                        className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
                      >
                        {deleteMutation.isPending ? (
                          <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                        ) : (
                          <Trash2 className="mr-2 h-4 w-4" />
                        )}
                        Supprimer définitivement
                      </AlertDialogAction>
                    </AlertDialogFooter>
                  </AlertDialogContent>
                </AlertDialog>
              )}
            </div>
          </div>
        </div>
      </main>
    </div>
  );
}
