import { useAuth } from "@/_core/hooks/useAuth";
import DataPrivacyValidationDialog from "@/components/DataPrivacyValidationDialog";
import { AuthenticatedPageSkeleton } from "@/components/AuthenticatedPageSkeleton";
import { PortalDashboardHeader, PortalMetricTile, PortalSectionIntro, PortalSurface } from "@/components/portal/PortalSurface";
import { ProfileRequiredState } from "@/components/ProfileRequiredState";
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,
  buildReservationSalleTitle,
  emptyReservationSalleFormData,
  listReservationDates,
  sallesMJS,
  syncReservationSalleDailySlots,
  validateReservationSalleFormInput,
} from "@/lib/reservationSalle";
import { trpc } from "@/lib/trpc";
import { getFriendlyActionError } from "@/lib/userFeedback";
import { buildDataPrivacyConsent } from "@shared/privacyCompliance";
import { useViewportFlags } from "@/hooks/useMobile";
import { cn } from "@/lib/utils";
import ccdsLogo from "@/assets/ccds.png";
import { ArrowLeft, Building2, CalendarDays, CheckCircle, Clock, Loader2, MapPin, Send, Trash2, Users } from "lucide-react";
import { useEffect, useMemo, useState } from "react";
import { Link, useLocation } from "wouter";
import { toast } from "sonner";

const RESERVATION_SALLE_DRAFT_KEY = "reservation-salle-draft";

export default function ReservationSalle() {
  const [, setLocation] = useLocation();
  const { user } = useAuth();
  const { isMobile, isTablet } = useViewportFlags();
  const { data: association, isLoading: loadingAssociation } = trpc.association.getMyProfile.useQuery();
  const { data: documents } = trpc.document.getMyDocuments.useQuery();
  const utils = trpc.useUtils();

  const [step, setStep] = useState(1);
  const [privacyDialogOpen, setPrivacyDialogOpen] = useState(false);
  const [pendingDraftMode, setPendingDraftMode] = useState(false);
  const [selectedSalles, setSelectedSalles] = useState<string[]>([]);
  const [formData, setFormData] = useState(emptyReservationSalleFormData());
  const [selectedDocuments, setSelectedDocuments] = useState<number[]>([]);

  const createMutation = trpc.request.create.useMutation({
    onSuccess: (data) => {
      sessionStorage.removeItem(RESERVATION_SALLE_DRAFT_KEY);
      if (data.submitted) {
        toast.success('Demande envoyée à l\'administration avec succès !');
      } else {
        toast.success('Brouillon enregistré avec succès !');
      }
      setLocation(`/dashboard/requests/${data.id}?submitted=${data.submitted ? "1" : "0"}&source=reservation-salle`);
    },
    onError: (error) => {
      toast.error(
        getFriendlyActionError(
          error,
          "Impossible d'enregistrer la réservation pour le moment. Vérifiez les informations de période, de salle et de documents puis réessayez.",
          {
            invalidInputMessage:
              "Impossible d'envoyer la réservation : merci de compléter la période, le motif et les salles souhaitées.",
          }
        )
      );
    },
  });

  // Minimum date = 15 days from now
  const minDate = useMemo(() => {
    const d = new Date();
    d.setDate(d.getDate() + 15);
    return d.toISOString().split('T')[0];
  }, []);
  const reservationDates = useMemo(
    () => listReservationDates(formData.dateReservation, formData.dateFinReservation),
    [formData.dateReservation, formData.dateFinReservation]
  );
  const canUseDetailedSchedule = reservationDates.length > 1;

  useEffect(() => {
    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,
      };
    });
  }, [
    formData.useDetailedSchedule,
    formData.dateReservation,
    formData.dateFinReservation,
    formData.heureDebut,
    formData.heureFin,
  ]);

  useEffect(() => {
    const savedDraft = sessionStorage.getItem(RESERVATION_SALLE_DRAFT_KEY);
    if (!savedDraft) return;

    try {
      const parsed = JSON.parse(savedDraft);
      if (parsed?.formData) {
        setFormData((prev) => ({ ...prev, ...parsed.formData }));
      }
      if (Array.isArray(parsed?.selectedSalles)) {
        setSelectedSalles(parsed.selectedSalles);
      }
      if (Array.isArray(parsed?.selectedDocuments)) {
        setSelectedDocuments(parsed.selectedDocuments);
      }
      if (typeof parsed?.step === "number" && parsed.step >= 1 && parsed.step <= 3) {
        setStep(parsed.step);
      }
    } catch {
      sessionStorage.removeItem(RESERVATION_SALLE_DRAFT_KEY);
    }
  }, []);

  const saveDraftAndOpenDocuments = () => {
    sessionStorage.setItem(
      RESERVATION_SALLE_DRAFT_KEY,
      JSON.stringify({
        step,
        selectedSalles,
        formData,
        selectedDocuments,
      })
    );
    setLocation("/dashboard/documents?returnTo=/dashboard/reservation-salle");
  };

  const toggleSalle = (salleId: string) => {
    setSelectedSalles(prev =>
      prev.includes(salleId)
        ? prev.filter(id => id !== salleId)
        : [...prev, salleId]
    );
  };

  const handleSubmit = (asBrouillon: boolean = false) => {
    if (!association) {
      toast.error('Veuillez compléter votre profil association');
      return;
    }

    const validationError = validateReservationSalleFormInput(formData, selectedSalles);
    if (validationError) {
      toast.error(validationError);
      return;
    }

    setPendingDraftMode(asBrouillon);
    setPrivacyDialogOpen(true);
  };

  const submitReservationWithPrivacyConsent = () => {
    if (!association) return;

    const formDataJson = JSON.stringify(
      buildReservationSallePayload({
        association,
        formData,
        selectedSalles,
      })
    );

    const titre = buildReservationSalleTitle(selectedSalles, formData.dateReservation);

    createMutation.mutate({
      type: 'demande_salle' as any,
      titre,
      description: formData.motifReservation,
      formData: formDataJson,
      documentsJoints: selectedDocuments.length > 0 ? selectedDocuments : undefined,
      submitImmediately: !pendingDraftMode,
      privacyConsent: buildDataPrivacyConsent("create_request"),
    });
  };

  if (loadingAssociation) {
    return (
      <div className="portal-immersive-page min-h-screen">
        <PortalDashboardHeader
          title="Réservation d'un local"
          description="Chargement de votre dossier"
        />
        <main className="container py-8">
          <div className="mx-auto max-w-5xl">
            <AuthenticatedPageSkeleton
              message="Chargement de votre profil association et des paramètres de réservation..."
              cards={2}
              formRows={5}
            />
          </div>
        </main>
      </div>
    );
  }

  if (!association) {
    return (
      <div className="portal-immersive-page min-h-screen">
        <PortalDashboardHeader title="Réservation de salle" />
        <main className="container py-8">
          <ProfileRequiredState
            title="Complétez votre fiche avant de réserver une salle"
            description="La réservation de salle utilise vos coordonnées, les responsables de l'association et les informations de contact pour préparer un dossier clair dès la première étape."
            icon={CalendarDays}
            highlights={[
              "Le service d'accueil récupère directement votre identité associative et le bon contact.",
              "La réservation sera plus rapide à instruire si le représentant légal et l'adresse sont déjà renseignés.",
              "Vous évitez les allers-retours sur les informations essentielles avant l'envoi du devis.",
              "Une fois votre fiche prête, le parcours salle reste prérempli pour vos prochaines réservations.",
            ]}
          />
        </main>
      </div>
    );
  }

  return (
    <div className="portal-immersive-page min-h-screen">
      <PortalDashboardHeader
        tourId="reservation-header"
        title="Réservation d'un local"
        description={`Maison de la Jeunesse des Savanes - Étape ${step} sur 3`}
        actions={
          <div className="flex items-start gap-2 rounded-xl border border-amber-200 bg-amber-50 px-3 py-2 text-xs text-amber-900 sm:items-center">
            <CalendarDays className="mt-0.5 h-4 w-4 shrink-0 text-amber-600 sm:mt-0" />
            <span>Réserve au moins 15 jours avant la date souhaitée.</span>
          </div>
        }
      />

      {/* Progress bar */}
      <div className="bg-white border-b">
        <div className="container py-2">
          <div className="flex items-center gap-2 overflow-x-auto pb-1 sm:overflow-visible">
            {[
              { num: 1, label: 'Salle' },
              { num: 2, label: 'Détails' },
              { num: 3, label: 'Récapitulatif' },
            ].map((s) => (
              <div key={s.num} className="min-w-[112px] flex-1 sm:min-w-0">
                <div className={`h-1.5 rounded-full transition-colors ${s.num <= step ? 'bg-[oklch(0.25_0.05_265)]' : 'bg-muted'}`} />
                <p className={`text-xs mt-1 text-center ${s.num <= step ? 'text-[oklch(0.25_0.05_265)] font-medium' : 'text-muted-foreground'}`}>
                  {s.label}
                </p>
              </div>
            ))}
          </div>
        </div>
      </div>

      <main className={cn("container py-6 sm:py-8", (isMobile || isTablet) && "pb-28")}>
        {/* Step 1: Select salles */}
        {step === 1 && (
          <div className="max-w-3xl mx-auto space-y-6">
            <PortalSurface
              className="border-primary/10 bg-gradient-to-r from-primary/10 via-white to-primary/5"
              bodyClassName="space-y-5"
            >
              <div className="grid gap-4 md:grid-cols-3">
                <PortalMetricTile label="Étape active" value={step} detail="Choix des locaux" tone="info" />
                <PortalMetricTile label="Locaux choisis" value={selectedSalles.length} detail="Sélection en cours" tone="success" />
                <PortalMetricTile label="Préavis minimum" value="15 j" detail="Avant la date souhaitée" tone="warning" />
              </div>
              <div className="rounded-xl border border-white/80 bg-white/85 px-4 py-4 shadow-sm">
                <div className="flex items-start gap-3">
                  <Building2 className="mt-0.5 h-5 w-5 text-[oklch(0.25_0.05_265)]" />
                  <div className="text-sm">
                    <p className="font-medium text-[oklch(0.25_0.05_265)]">
                      Demande au nom de : {association.nomAssociation}
                    </p>
                    {association.adresse && (
                      <p className="text-muted-foreground">
                        {association.adresse}, {association.codePostal} {association.ville}
                      </p>
                    )}
                    <p className="mt-1 text-muted-foreground">
                      Vos coordonnées et votre association seront reprises automatiquement dans le dossier de réservation.
                    </p>
                  </div>
                </div>
              </div>
            </PortalSurface>

            <PortalSectionIntro
              eyebrow="Sélection"
              title="Quel local souhaitez-vous réserver ?"
              description="Sélectionnez un ou plusieurs locaux à la Maison de la Jeunesse des Savanes."
            />

            <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
              {sallesMJS.map((salle) => {
                const isSelected = selectedSalles.includes(salle.id);
                return (
                  <Card
                    key={salle.id}
                    className={`cursor-pointer rounded-2xl bg-white/96 transition-all hover:-translate-y-0.5 hover:shadow-md ${
                      isSelected
                        ? 'border-[oklch(0.25_0.05_265)] ring-2 ring-[oklch(0.25_0.05_265)]/20 bg-[oklch(0.25_0.05_265)]/5'
                        : 'hover:border-[oklch(0.25_0.05_265)]/50'
                    }`}
                    onClick={() => toggleSalle(salle.id)}
                  >
                    <CardContent className="p-3.5">
                      <div className="flex items-start gap-3">
                        <div className="flex items-center justify-center w-10 h-10 rounded-lg bg-muted text-xl">
                          {salle.icon}
                        </div>
                        <div className="flex-1">
                          <div className="flex items-center gap-2">
                            <h3 className="font-semibold">{salle.nom}</h3>
                            {isSelected && (
                              <CheckCircle className="h-4 w-4 text-[oklch(0.25_0.05_265)]" />
                            )}
                          </div>
                          <p className="text-sm text-muted-foreground">{salle.description}</p>
                          <p className="text-xs text-muted-foreground mt-1">{salle.capacite}</p>
                        </div>
                      </div>
                    </CardContent>
                  </Card>
                );
              })}
            </div>

            {selectedSalles.length > 0 && (
              <div className={cn(
                "flex flex-col gap-3 pt-4 sm:flex-row sm:items-center sm:justify-between",
                isMobile && "fixed inset-x-0 bottom-0 z-20 border-t border-border bg-white/96 px-4 py-3 shadow-[0_-12px_30px_rgba(15,23,42,0.08)] backdrop-blur"
              )}>
                <p className="text-sm text-muted-foreground">
                  {selectedSalles.length} local(aux) sélectionné(s)
                </p>
                <Button
                  onClick={() => setStep(2)}
                  className="w-full min-h-11 bg-[oklch(0.25_0.05_265)] hover:bg-[oklch(0.30_0.05_265)] sm:w-auto"
                >
                  Continuer
                  <ArrowLeft className="ml-2 h-4 w-4 rotate-180" />
                </Button>
              </div>
            )}
          </div>
        )}

        {/* Step 2: Fill details */}
        {step === 2 && (
          <div className="max-w-2xl mx-auto space-y-6">
            <PortalSurface
              className="border-primary/10 bg-gradient-to-r from-primary/10 via-white to-primary/5"
              bodyClassName="space-y-5"
            >
              <PortalSectionIntro
                eyebrow="Pré-remplissage"
                title="Votre dossier salle reprend déjà les bons repères"
                description="Vérifiez les informations de votre association et les locaux retenus avant de passer au détail de la réservation."
                aside="Vous pouvez corriger votre fiche ou revenir à l’étape précédente sans perdre le fil du dossier."
              />

              <div className="grid gap-4 lg:grid-cols-2">
                <div className="rounded-2xl border border-white/80 bg-white/90 p-4 shadow-sm">
                  <div className="flex items-center gap-2 text-base font-semibold text-[oklch(0.25_0.05_265)]">
                    <Building2 className="h-5 w-5" />
                    <span>Base association</span>
                  </div>
                  <div className="mt-4 grid gap-3 text-sm">
                    <div className="grid gap-3 sm:grid-cols-2">
                      <div className="rounded-xl border border-slate-200 bg-slate-50/80 px-3 py-2.5">
                        <span className="text-[11px] uppercase tracking-wide text-muted-foreground">Association</span>
                        <p className="mt-1 font-medium">{association.nomAssociation}</p>
                      </div>
                      <div className="rounded-xl border border-slate-200 bg-slate-50/80 px-3 py-2.5">
                        <span className="text-[11px] uppercase tracking-wide text-muted-foreground">Commune</span>
                        <p className="mt-1 font-medium">{association.ville || "Non renseignée"}</p>
                      </div>
                    </div>
                    <div className="rounded-xl border border-slate-200 bg-slate-50/80 px-3 py-2.5">
                      <span className="text-[11px] uppercase tracking-wide text-muted-foreground">Adresse</span>
                      <p className="mt-1 font-medium">
                        {association.adresse ? `${association.adresse}, ${association.codePostal} ${association.ville}` : "Non renseignée"}
                      </p>
                    </div>
                    <div className="grid gap-3 sm:grid-cols-2">
                      <div className="rounded-xl border border-slate-200 bg-slate-50/80 px-3 py-2.5">
                        <span className="text-[11px] uppercase tracking-wide text-muted-foreground">Représentant légal</span>
                        <p className="mt-1 font-medium">{association.nomRepresentant || "Non renseigné"}</p>
                      </div>
                      <div className="rounded-xl border border-slate-200 bg-slate-50/80 px-3 py-2.5">
                        <span className="text-[11px] uppercase tracking-wide text-muted-foreground">Téléphone</span>
                        <p className="mt-1 font-medium">{association.telephone || "Non renseigné"}</p>
                      </div>
                    </div>
                  </div>
                  <div className="mt-4 border-t border-slate-200 pt-3">
                    <Link href="/dashboard/profile" className="text-xs font-medium text-primary hover:underline">
                      Mettre à jour ma fiche association
                    </Link>
                  </div>
                </div>

                <div className="rounded-2xl border border-white/80 bg-white/90 p-4 shadow-sm">
                  <div className="flex items-center gap-2 text-base font-semibold text-[oklch(0.25_0.05_265)]">
                    <MapPin className="h-5 w-5" />
                    <span>Local(aux) sollicités</span>
                  </div>
                  <p className="mt-2 text-sm text-muted-foreground">
                    Vous pouvez revenir à l’étape précédente si vous devez ajuster la sélection.
                  </p>
                  <div className="mt-4 flex flex-wrap gap-2">
                    {selectedSalles.map(id => {
                      const salle = sallesMJS.find(s => s.id === id);
                      return salle ? (
                        <span
                          key={id}
                          className="inline-flex items-center gap-1.5 rounded-full border border-[oklch(0.25_0.05_265)]/15 bg-[oklch(0.25_0.05_265)]/8 px-3 py-1.5 text-sm font-medium text-[oklch(0.25_0.05_265)]"
                        >
                          {salle.icon} {salle.nom}
                        </span>
                      ) : null;
                    })}
                  </div>
                  <div className="mt-4 rounded-xl border border-dashed border-slate-200 bg-slate-50/70 px-3 py-3 text-sm text-muted-foreground">
                    La suite permet de préciser la période, les horaires et les besoins utiles au traitement de votre réservation.
                  </div>
                </div>
              </div>
            </PortalSurface>

            {/* Reservation details */}
            <Card className="rounded-2xl bg-white/96">
              <CardHeader>
                <CardTitle className="flex items-center gap-2 text-base">
                  <CalendarDays className="h-5 w-5 text-[oklch(0.25_0.05_265)]" />
                  Détails de la réservation
                </CardTitle>
                <CardDescription>
                  Remplissez les informations relatives à votre réservation
                </CardDescription>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="space-y-2">
                  <Label htmlFor="motif">Motif de la réservation *</Label>
                  <Textarea
                    id="motif"
                    value={formData.motifReservation}
                    onChange={(e) => setFormData(prev => ({ ...prev, motifReservation: e.target.value }))}
                    placeholder="Ex: Assemblée générale annuelle, Entraînement sportif, Événement culturel..."
                    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}
                      min={minDate}
                      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,
                        };
                      })}
                    />
                    <p className="text-xs text-muted-foreground">Minimum 15 jours à l'avance</p>
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="dateFinReservation">Date de fin *</Label>
                    <Input
                      id="dateFinReservation"
                      type="date"
                      min={formData.dateReservation || minDate}
                      value={formData.dateFinReservation}
                      onChange={(e) => setFormData(prev => ({ ...prev, dateFinReservation: e.target.value }))}
                    />
                    <p className="text-xs text-muted-foreground">Si la réservation dure plusieurs jours</p>
                  </div>
                </div>

                <div className="grid gap-4 md:grid-cols-2">
                  <div className="space-y-2">
                    <Label htmlFor="heureDebut" className="flex items-center gap-1.5">
                      <Clock className="h-3.5 w-3.5" />
                      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" className="flex items-center gap-1.5">
                      <Clock className="h-3.5 w-3.5" />
                      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 ? (
                  <Card className="border-[oklch(0.25_0.05_265)]/20 bg-[oklch(0.25_0.05_265)]/5">
                    <CardContent className="pt-5 space-y-4">
                      <div className="flex items-start gap-3">
                        <Checkbox
                          id="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="useDetailedSchedule" className="cursor-pointer">
                            Mes horaires varient selon les jours
                          </Label>
                          <p className="text-xs text-muted-foreground">
                            Laissez ce mode désactivé si le même créneau s'applique à 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>
                          <div className="rounded-lg border bg-white px-3 py-2 text-xs text-muted-foreground">
                            Chaque journée reste modifiable. Les horaires communs servent seulement de base.
                          </div>
                          <div className="space-y-3">
                            {formData.horairesParJour.map((slot, index) => (
                              <div key={slot.date} className="rounded-xl border bg-white 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={`slot-start-${slot.date}`}>Début</Label>
                                    <Input
                                      id={`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={`slot-end-${slot.date}`}>Fin</Label>
                                    <Input
                                      id={`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>
                        </div>
                      ) : null}
                    </CardContent>
                  </Card>
                ) : null}

                <div className="space-y-2">
                  <Label htmlFor="nombreParticipants" className="flex items-center gap-1.5">
                    <Users className="h-3.5 w-3.5" />
                    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="besoinsComplementaires">Besoins complémentaires</Label>
                  <Textarea
                    id="besoinsComplementaires"
                    value={formData.besoinsComplementaires}
                    onChange={(e) => setFormData((prev) => ({ ...prev, besoinsComplementaires: e.target.value }))}
                    placeholder="Ex: hall, dojo, espace d'accueil, besoins techniques spécifiques..."
                    rows={2}
                  />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="materiel">Matériel nécessaire</Label>
                  <Textarea
                    id="materiel"
                    value={formData.materielNecessaire}
                    onChange={(e) => setFormData(prev => ({ ...prev, materielNecessaire: e.target.value }))}
                    placeholder="Ex: Tables, chaises, sono, 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>

              </CardContent>
            </Card>

            {/* Documents */}
            <Card>
              <CardHeader className="pb-3">
                <CardTitle className="text-base">Documents à joindre (optionnel)</CardTitle>
                <CardDescription>
                  Joignez les documents utiles à votre demande
                </CardDescription>
              </CardHeader>
              <CardContent>
                {documents && documents.length > 0 ? (
                  <div className="space-y-2">
                    {documents.map((doc) => (
                      <div key={doc.id} className="flex items-center space-x-3 p-2.5 rounded-lg border hover:bg-muted/50">
                        <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 text-sm">{doc.nom}</div>
                          <div className="text-xs text-muted-foreground">{doc.type}</div>
                        </Label>
                      </div>
                    ))}
                  </div>
                ) : (
                  <div className="text-center py-4 text-sm text-muted-foreground">
                    <p>Aucun document disponible.</p>
                    <button
                      type="button"
                      onClick={saveDraftAndOpenDocuments}
                      className="text-primary hover:underline"
                    >
                      Téléverser des documents
                    </button>
                  </div>
                )}
              </CardContent>
            </Card>

            <div className={cn(
              "flex flex-col-reverse gap-3 sm:flex-row sm:justify-between",
              isMobile && "fixed inset-x-0 bottom-0 z-20 border-t border-border bg-white/96 px-4 py-3 shadow-[0_-12px_30px_rgba(15,23,42,0.08)] backdrop-blur"
            )}>
              <Button variant="outline" onClick={() => setStep(1)} className="w-full min-h-11 sm:w-auto">
                <ArrowLeft className="mr-2 h-4 w-4" />
                Retour
              </Button>
              <Button
                onClick={() => {
                  const validationError = validateReservationSalleFormInput(formData, selectedSalles);
                  if (validationError) {
                    toast.error(validationError);
                    return;
                  }
                  setStep(3);
                }}
                className="w-full min-h-11 bg-[oklch(0.25_0.05_265)] hover:bg-[oklch(0.30_0.05_265)] sm:w-auto"
              >
                Voir le récapitulatif
                <ArrowLeft className="ml-2 h-4 w-4 rotate-180" />
              </Button>
            </div>
          </div>
        )}

        {/* Step 3: Summary and submit */}
        {step === 3 && (
          <div className="max-w-2xl mx-auto space-y-6">
            {/* Official header */}
            <Card className="overflow-hidden rounded-3xl border-[oklch(0.25_0.05_265)]/30">
              <div className="bg-[oklch(0.25_0.05_265)] text-white px-6 py-4">
                <div className="text-center">
                  <div className="mb-3 flex justify-center">
                    <img src={ccdsLogo} alt="Logo CCDS" className="h-20 w-auto object-contain rounded bg-white/95 px-2 py-1" />
                  </div>
                  <p className="text-xs uppercase tracking-wider opacity-80">Communauté de Communes Des Savanes</p>
                  <h2 className="text-lg font-bold mt-1">Formulaire de Réservation d'un Local</h2>
                  <p className="text-sm opacity-80">Maison de la Jeunesse des Savanes</p>
                </div>
              </div>
              <CardContent className="p-6 space-y-6">
                {/* Association info */}
                <div>
                  <h3 className="font-semibold text-sm uppercase text-muted-foreground mb-3">Informations de l'association</h3>
                  <div className="grid gap-2 text-sm">
                    <div className="flex flex-col gap-1 border-b border-dashed py-1.5 sm:flex-row sm:items-start sm:justify-between">
                      <span className="text-muted-foreground">Nom de l'association :</span>
                      <span className="font-medium">{association.nomAssociation}</span>
                    </div>
                    <div className="flex flex-col gap-1 border-b border-dashed py-1.5 sm:flex-row sm:items-start sm:justify-between">
                      <span className="text-muted-foreground">Adresse :</span>
                      <span className="font-medium sm:text-right">
                        {association.adresse ? `${association.adresse}, ${association.codePostal} ${association.ville}` : '-'}
                      </span>
                    </div>
                    <div className="flex justify-between py-1.5 border-b border-dashed">
                      <span className="text-muted-foreground">Commune du siège :</span>
                      <span className="font-medium">{association.ville || '-'}</span>
                    </div>
                    <div className="flex justify-between py-1.5 border-b border-dashed">
                      <span className="text-muted-foreground">Représentant légal :</span>
                      <span className="font-medium">{association.nomRepresentant || '-'}</span>
                    </div>
                  </div>
                </div>

                <Separator />

                {/* Local sollicité */}
                <div>
                  <h3 className="font-semibold text-sm uppercase text-muted-foreground mb-3">Local(aux) sollicité(s)</h3>
                  <div className="flex flex-wrap gap-2">
                    {selectedSalles.map(id => {
                      const salle = sallesMJS.find(s => s.id === id);
                      return salle ? (
                        <span
                          key={id}
                          className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full bg-[oklch(0.25_0.05_265)]/10 text-[oklch(0.25_0.05_265)] text-sm font-medium"
                        >
                          <CheckCircle className="h-3.5 w-3.5" />
                          {salle.nom}
                        </span>
                      ) : null;
                    })}
                  </div>
                </div>

                <Separator />

                {/* Reservation details */}
                <div>
                  <h3 className="font-semibold text-sm uppercase text-muted-foreground mb-3">Détails de la réservation</h3>
                  <div className="grid gap-2 text-sm">
                    <div className="flex flex-col gap-1 border-b border-dashed py-1.5 sm:flex-row sm:items-start sm:justify-between">
                      <span className="text-muted-foreground">Motif :</span>
                      <span className="font-medium sm:max-w-[60%] sm:text-right">{formData.motifReservation}</span>
                    </div>
                    <div className="flex justify-between py-1.5 border-b border-dashed">
                      <span className="text-muted-foreground">Date :</span>
                      <span className="font-medium">
                        {new Date(formData.dateReservation).toLocaleDateString('fr-FR', { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' })}
                        {formData.dateFinReservation && formData.dateFinReservation !== formData.dateReservation && (
                          <> au {new Date(formData.dateFinReservation).toLocaleDateString('fr-FR', { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' })}</>
                        )}
                      </span>
                    </div>
                    {!formData.useDetailedSchedule && (formData.heureDebut || formData.heureFin) && (
                      <div className="flex justify-between py-1.5 border-b border-dashed">
                        <span className="text-muted-foreground">Créneau commun :</span>
                        <span className="font-medium">
                          {formData.heureDebut || '?'} - {formData.heureFin || '?'}
                        </span>
                      </div>
                    )}
                    {formData.useDetailedSchedule && formData.horairesParJour.length > 0 && (
                      <div className="py-1.5 border-b border-dashed">
                        <span className="text-muted-foreground block mb-2">Créneaux détaillés :</span>
                        <div className="space-y-2">
                          {formData.horairesParJour.map((slot) => (
                            <div key={slot.date} className="flex flex-col gap-1 rounded-md bg-muted/40 px-3 py-2 sm:flex-row sm:justify-between sm:gap-4">
                              <span className="font-medium">
                                {new Date(`${slot.date}T12:00:00`).toLocaleDateString('fr-FR', {
                                  weekday: 'short',
                                  day: 'numeric',
                                  month: 'long',
                                })}
                              </span>
                              <span>{slot.heureDebut || '?'} - {slot.heureFin || '?'}</span>
                            </div>
                          ))}
                        </div>
                      </div>
                    )}
                    {formData.nombreParticipants && (
                      <div className="flex justify-between py-1.5 border-b border-dashed">
                        <span className="text-muted-foreground">Participants :</span>
                        <span className="font-medium">{formData.nombreParticipants} personnes</span>
                      </div>
                    )}
                    {formData.besoinsComplementaires && (
                      <div className="flex flex-col gap-1 border-b border-dashed py-1.5 sm:flex-row sm:items-start sm:justify-between">
                        <span className="text-muted-foreground">Besoins complémentaires :</span>
                        <span className="font-medium sm:max-w-[60%] sm:text-right">{formData.besoinsComplementaires}</span>
                      </div>
                    )}
                    {formData.materielNecessaire && (
                      <div className="flex flex-col gap-1 border-b border-dashed py-1.5 sm:flex-row sm:items-start sm:justify-between">
                        <span className="text-muted-foreground">Matériel :</span>
                        <span className="font-medium sm:max-w-[60%] sm:text-right">{formData.materielNecessaire}</span>
                      </div>
                    )}
                    {formData.observations && (
                      <div className="flex flex-col gap-1 border-b border-dashed py-1.5 sm:flex-row sm:items-start sm:justify-between">
                        <span className="text-muted-foreground">Observations :</span>
                        <span className="font-medium sm:max-w-[60%] sm:text-right">{formData.observations}</span>
                      </div>
                    )}
                    <div className="flex justify-between py-1.5 border-b border-dashed">
                      <span className="text-muted-foreground">Documents joints :</span>
                      <span className="font-medium">{selectedDocuments.length}</span>
                    </div>
                  </div>
                </div>

                {/* DSU section */}
                <div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
                  <h3 className="font-semibold text-sm text-blue-800 mb-2">
                    Cadre réservé à la Direction des Services aux Usagers (DSU)
                  </h3>
                  <p className="text-xs text-blue-600">
                    Ce cadre sera complété par l'administration lors du traitement de votre demande.
                  </p>
                  <div className="grid gap-2 mt-3 text-sm text-blue-700">
                    <div className="flex items-center gap-2">
                      <span>Date de réception : </span>
                      <span className="border-b border-dashed border-blue-300 flex-1" />
                    </div>
                    <div className="flex items-center gap-2">
                      <span>Décision : </span>
                      <span className="border-b border-dashed border-blue-300 flex-1" />
                    </div>
                  </div>
                </div>
              </CardContent>
            </Card>

            <div className={cn(
              "flex flex-col gap-3 sm:flex-row sm:justify-between",
              isMobile && "fixed inset-x-0 bottom-0 z-20 border-t border-border bg-white/96 px-4 py-3 shadow-[0_-12px_30px_rgba(15,23,42,0.08)] backdrop-blur"
            )}>
              <div className="flex flex-col gap-2 sm:flex-row">
                <Button variant="outline" onClick={() => setStep(2)} className="w-full min-h-11 sm:w-auto">
                  <ArrowLeft className="mr-2 h-4 w-4" />
                  Modifier
                </Button>
                <Link href="/dashboard/requests">
                  <Button variant="destructive" className="w-full min-h-11 sm:w-auto">
                    <Trash2 className="mr-2 h-4 w-4" />
                    Annuler
                  </Button>
                </Link>
              </div>
              <div className="flex flex-col gap-3 sm:flex-row">
                <Button
                  variant="outline"
                  onClick={() => handleSubmit(true)}
                  disabled={createMutation.isPending}
                  className="w-full min-h-11 sm:w-auto"
                >
                  {createMutation.isPending && pendingDraftMode ? (
                    <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                  ) : null}
                  {createMutation.isPending && pendingDraftMode ? "Enregistrement en cours..." : "Enregistrer en brouillon"}
                </Button>
                <Button
                  onClick={() => handleSubmit(false)}
                  disabled={createMutation.isPending}
                  className="w-full min-h-11 bg-[oklch(0.25_0.05_265)] hover:bg-[oklch(0.30_0.05_265)] sm:w-auto"
                >
                  {createMutation.isPending ? (
                    <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                  ) : (
                    <Send className="mr-2 h-4 w-4" />
                  )}
                  {createMutation.isPending && !pendingDraftMode ? "Envoi en cours..." : "Envoyer la demande"}
                </Button>
              </div>
            </div>
          </div>
        )}
      </main>

      <DataPrivacyValidationDialog
        open={privacyDialogOpen}
        onOpenChange={setPrivacyDialogOpen}
        context="create_request"
        confirmLabel={pendingDraftMode ? "Valider et enregistrer le brouillon" : "Valider et envoyer la demande"}
        onConfirm={submitReservationWithPrivacyConsent}
      />
    </div>
  );
}
