import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Textarea } from "@/components/ui/textarea";
import { Separator } from "@/components/ui/separator";
import ReservationCalendar from "@/components/ReservationCalendar";
import { trpc } from "@/lib/trpc";
import { formatReservationSallePeriod, getReservationSalleScheduleSummary } from "@/lib/reservationSalle";
import { SALLE_WORKFLOW_PAYMENT_STATUS_LABELS, type SalleWorkflowPaymentStatus } from "@shared/sallePricing";
import {
  ArrowLeft,
  Calendar,
  CheckCircle,
  FileText,
  Loader2,
  RotateCcw,
  ShieldCheck,
  UserPlus,
  Users,
  X,
} from "lucide-react";
import { useEffect, useMemo, useState } from "react";
import { Link, useLocation } from "wouter";
import { toast } from "sonner";

type DirectorSignatureAdminProps = {
  user: {
    role?: string | null;
    canSignSalle?: boolean | null;
    name?: string | null;
  };
};

const requestTypeLabels: Record<string, string> = {
  demande_salle: "Réservation de salle",
  demande_materiel_evenementiel: "Matériel événementiel",
  subvention_fonctionnement: "Subvention fonctionnement",
  subvention_projet: "Subvention projet",
  agrement_jeunesse_education: "Agrément JEP",
  agrement_sport: "Agrément sport",
  autorisation_occupation: "Autorisation d'occupation",
  autre: "Autre",
};

const statusLabels: Record<string, string> = {
  brouillon: "Brouillon",
  soumise: "Soumise",
  en_cours_traitement: "En cours",
  information_complementaire: "Information complémentaire",
  validee: "Validée",
  refusee: "Refusée",
  annulee: "Annulée",
};

function formatDateTime(value: string | Date | null | undefined) {
  if (!value) return "-";
  try {
    return new Date(value).toLocaleString("fr-FR", {
      day: "2-digit",
      month: "2-digit",
      year: "numeric",
      hour: "2-digit",
      minute: "2-digit",
    });
  } catch {
    return String(value);
  }
}

function formatDate(value: string | Date | null | undefined) {
  if (!value) return "-";
  try {
    return new Date(value).toLocaleDateString("fr-FR", {
      day: "2-digit",
      month: "2-digit",
      year: "numeric",
    });
  } catch {
    return String(value);
  }
}

function formatCurrency(cents: number | null | undefined) {
  if (!Number.isFinite(Number(cents))) return "-";
  return new Intl.NumberFormat("fr-FR", {
    style: "currency",
    currency: "EUR",
  }).format(Number(cents) / 100);
}

const paymentStatusClasses: Record<SalleWorkflowPaymentStatus, string> = {
  en_attente_paiement: "border-amber-200 bg-amber-100 text-amber-900",
  paiement_partiel: "border-orange-200 bg-orange-100 text-orange-900",
  paiement_recu: "border-sky-200 bg-sky-100 text-sky-900",
  paiement_valide: "border-emerald-200 bg-emerald-100 text-emerald-900",
};

export default function DirectorSignatureAdmin({ user }: DirectorSignatureAdminProps) {
  const utils = trpc.useUtils();
  const [, setLocation] = useLocation();
  const { data: delegation } = trpc.salleSignature.getDelegation.useQuery(undefined, {
    enabled: user.role === "directrice",
  });
  const { data: signatureQueue, isLoading } = trpc.request.getSalleSignatureQueue.useQuery(undefined, {
    refetchInterval: 30_000,
  });
  const { data: pastRequests, isLoading: pastRequestsLoading } = trpc.request.getPastForSignature.useQuery();
  const { data: billingEntries, isLoading: billingEntriesLoading } = trpc.request.getSalleBillingBoard.useQuery(undefined, {
    refetchInterval: 30_000,
  });

  const [candidateUserId, setCandidateUserId] = useState<string>("none");
  const [delegateEmail, setDelegateEmail] = useState("");
  const [returnComments, setReturnComments] = useState<Record<number, string>>({});

  useEffect(() => {
    setCandidateUserId("none");
  }, [delegation?.delegatedUsers]);

  const setDelegationMutation = trpc.salleSignature.setDelegation.useMutation({
    onSuccess: () => {
      toast.success("Délégation de signature mise à jour");
      utils.salleSignature.getDelegation.invalidate();
      utils.auth.me.invalidate();
    },
    onError: (error) => {
      toast.error(error.message || "Impossible d'enregistrer la délégation");
    },
  });

  const addDelegateByEmailMutation = trpc.salleSignature.addDelegateByEmail.useMutation({
    onSuccess: () => {
      toast.success("Adresse ajoutée aux signataires remplaçants");
      setDelegateEmail("");
      utils.salleSignature.getDelegation.invalidate();
      utils.auth.me.invalidate();
    },
    onError: (error) => {
      toast.error(error.message || "Impossible d'ajouter cette adresse");
    },
  });

  const removeDelegateMutation = trpc.salleSignature.removeDelegate.useMutation({
    onSuccess: () => {
      toast.success("Signataire remplaçant retiré");
      utils.salleSignature.getDelegation.invalidate();
      utils.auth.me.invalidate();
    },
    onError: (error) => {
      toast.error(error.message || "Impossible de retirer cette personne");
    },
  });

  const finalizeSalleReservationMutation = trpc.request.finalizeSalleReservation.useMutation({
    onSuccess: () => {
      toast.success("Demande signée. Le dossier revient à l’hôtesse pour l’envoi final.");
      utils.request.getSalleSignatureQueue.invalidate();
      utils.request.search.invalidate();
      utils.request.getPending.invalidate();
      utils.request.getPastForSignature.invalidate();
      utils.auth.me.invalidate();
    },
    onError: (error) => {
      toast.error(error.message || "Impossible de signer la demande");
    },
  });

  const returnSalleToHostessMutation = trpc.request.returnSalleToHostess.useMutation({
    onSuccess: () => {
      toast.success("Le dossier est revenu à l’hôtesse");
      utils.request.getSalleSignatureQueue.invalidate();
      utils.request.search.invalidate();
      utils.request.getPending.invalidate();
    },
    onError: (error) => {
      toast.error(error.message || "Impossible de renvoyer le dossier à l’hôtesse");
    },
  });

  const normalizedQueue = useMemo(() => {
    return (signatureQueue || []).map((entry) => {
      const period = formatReservationSallePeriod({
        dateReservation: entry.dateReservation,
        dateFinReservation: entry.dateFinReservation,
      });
      const schedule = getReservationSalleScheduleSummary({
        useDetailedSchedule: Boolean(entry.useDetailedSchedule),
        horairesParJour: Array.isArray(entry.horairesParJour) ? entry.horairesParJour : [],
        heureDebut: entry.heureDebut || "",
        heureFin: entry.heureFin || "",
      });
      return {
        ...entry,
        period,
        schedule,
        paymentLate: Boolean(
          entry.financialMode === "location_payante"
          && entry.paymentDueDate
          && !["paiement_recu", "paiement_valide"].includes(entry.paymentStatus || "")
          && entry.paymentDueDate < new Date().toISOString().slice(0, 10)
        ),
      };
    });
  }, [signatureQueue]);

  const delegatedUsers = delegation?.delegatedUsers || [];
  const availableCandidates = (delegation?.candidates || []).filter(
    (candidate) => !delegatedUsers.some((entry) => entry.id === candidate.id)
  );
  const billingCounts = useMemo(() => {
    const entries = billingEntries || [];
    return {
      all: entries.length,
      en_attente: entries.filter((entry) => entry.paymentStatus === "en_attente_paiement").length,
      en_retard: entries.filter((entry) => entry.isLate).length,
      recues: entries.filter((entry) => entry.paymentStatus === "paiement_recu").length,
      validees: entries.filter((entry) => entry.paymentStatus === "paiement_valide").length,
    };
  }, [billingEntries]);
  const directriceIndicators = useMemo(() => {
    const signedLate = (billingEntries || []).filter((entry) => entry.isLate).length;
    const locationsPayantes = (billingEntries || []).length;
    return {
      aSigner: normalizedQueue.length,
      paiementsEnAttente: billingCounts.en_attente + billingCounts.en_retard,
      locationsPayantes,
      tauxOccupation: locationsPayantes > 0
        ? Math.round((billingCounts.validees / Math.max(locationsPayantes, 1)) * 100)
        : 0,
      paiementsCritiques: signedLate,
    };
  }, [billingCounts.en_attente, billingCounts.en_retard, billingCounts.validees, billingEntries, normalizedQueue.length]);

  const handleAddExistingDelegate = () => {
    if (candidateUserId === "none") return;
    const nextIds = Array.from(
      new Set(delegatedUsers.map((entry) => entry.id).concat(Number(candidateUserId)))
    );
    setDelegationMutation.mutate({ delegateUserIds: nextIds });
  };

  const handleRemoveDelegate = (userId: number) => {
    removeDelegateMutation.mutate({ userId });
  };

  const handleAddDelegateEmail = () => {
    const normalizedEmail = delegateEmail.trim().toLowerCase();
    if (!normalizedEmail) {
      toast.error("Renseigne une adresse email");
      return;
    }
    addDelegateByEmailMutation.mutate({ email: normalizedEmail });
  };

  return (
    <div className="min-h-screen bg-background px-4 py-8 md:px-8">
      <div className="mx-auto flex max-w-6xl flex-col gap-6">
        <div className="flex flex-col gap-3 md:flex-row md:items-center md:justify-between">
          <div className="space-y-2">
            <div className="flex items-center gap-2">
              <ShieldCheck className="h-5 w-5 text-primary" />
              <h1 className="text-2xl font-semibold tracking-tight">Signature des demandes de salle</h1>
            </div>
            <p className="text-sm text-muted-foreground">
              Cet espace est réservé à la Directrice et, si besoin, aux personnes désignées pour signer en son absence.
            </p>
          </div>
          <div className="flex flex-wrap gap-2">
            <a href="#indicateurs">
              <Button variant="outline">
                <ShieldCheck className="mr-2 h-4 w-4" />
                Voir les statistiques
              </Button>
            </a>
            <a href="#facturation">
              <Button variant="outline">
                <FileText className="mr-2 h-4 w-4" />
                Consulter la facturation
              </Button>
            </a>
            <a href="#signature-queue">
              <Button>
                <CheckCircle className="mr-2 h-4 w-4" />
                Signer et valider
              </Button>
            </a>
            <a href="#signature-queue">
              <Button variant="outline">
                <RotateCcw className="mr-2 h-4 w-4" />
                Retour à l’accueil
              </Button>
            </a>
            <Button
              variant="outline"
              onClick={() => {
                if (typeof window !== "undefined") {
                  window.location.assign("/admin?tab=ccds-directory");
                }
              }}
            >
              <Users className="mr-2 h-4 w-4" />
              Annuaire CCDS
            </Button>
            <Link href="/dashboard">
              <Button variant="outline">
                <ArrowLeft className="mr-2 h-4 w-4" />
                Retour au tableau de bord
              </Button>
            </Link>
          </div>
        </div>

        <Card id="indicateurs" className="border-primary/10 bg-gradient-to-br from-primary/5 via-background to-background">
          <CardHeader>
            <CardTitle>Indicateurs clés Direction</CardTitle>
            <CardDescription>
              Les signaux à lire rapidement avant de signer, arbitrer ou vérifier la bonne préparation des dossiers.
            </CardDescription>
          </CardHeader>
          <CardContent className="grid gap-4 md:grid-cols-2 xl:grid-cols-4">
            <div className="rounded-lg border bg-background px-4 py-4">
              <p className="text-sm font-medium text-muted-foreground">À signer maintenant</p>
              <p className="mt-2 text-3xl font-semibold">{directriceIndicators.aSigner}</p>
              <p className="mt-2 text-xs text-muted-foreground">Dossiers déjà validés par l’association et transmis à la Direction.</p>
            </div>
            <div className="rounded-lg border bg-background px-4 py-4">
              <p className="text-sm font-medium text-muted-foreground">Paiements à surveiller</p>
              <p className="mt-2 text-3xl font-semibold">{directriceIndicators.paiementsEnAttente}</p>
              <p className="mt-2 text-xs text-muted-foreground">Locations payantes encore en attente ou en retard avant usage.</p>
            </div>
            <div className="rounded-lg border bg-background px-4 py-4">
              <p className="text-sm font-medium text-muted-foreground">Locations payantes</p>
              <p className="mt-2 text-3xl font-semibold">{directriceIndicators.locationsPayantes}</p>
              <p className="mt-2 text-xs text-muted-foreground">Dossiers facturés visibles dans la file de contrôle financier.</p>
            </div>
            <div className="rounded-lg border bg-background px-4 py-4">
              <p className="text-sm font-medium text-muted-foreground">Paiements validés</p>
              <p className="mt-2 text-3xl font-semibold">{directriceIndicators.tauxOccupation}%</p>
              <p className="mt-2 text-xs text-muted-foreground">Part des locations payantes déjà validées côté règlement.</p>
            </div>
          </CardContent>
        </Card>

        {directriceIndicators.paiementsCritiques > 0 && (
          <Card className="border-red-200 bg-red-50/70">
            <CardContent className="flex flex-col gap-3 p-4 md:flex-row md:items-center md:justify-between">
              <div>
                <p className="text-sm font-semibold text-red-800">Paiement non confirmé avant usage des lieux</p>
                <p className="text-sm text-red-700">
                  {directriceIndicators.paiementsCritiques} dossier(s) facturé(s) présentent un retard ou une validation manquante à vérifier avant utilisation.
                </p>
              </div>
              <a href="#facturation">
                <Button variant="outline" className="border-red-200 bg-white text-red-800 hover:bg-red-100">
                  Voir la facturation
                </Button>
              </a>
            </CardContent>
          </Card>
        )}

        {user.role === "directrice" && (
          <Card>
            <CardHeader>
              <CardTitle>Délégation de signature</CardTitle>
              <CardDescription>
                Ajoute les personnes qui peuvent signer à ta place. L’Accueil peut donc recevoir temporairement ce droit, sans récupérer tout l’accès administrateur.
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-5">
              <div className="grid gap-3 md:grid-cols-[minmax(0,1fr)_auto] md:items-end">
                <div className="space-y-2">
                  <Label htmlFor="delegate-email">Ajouter une adresse email</Label>
                  <Input
                    id="delegate-email"
                    type="email"
                    placeholder="prenom.nom@ccds-guyane.fr"
                    value={delegateEmail}
                    onChange={(event) => setDelegateEmail(event.target.value)}
                  />
                </div>
                <Button
                  onClick={handleAddDelegateEmail}
                  disabled={addDelegateByEmailMutation.isPending}
                >
                  {addDelegateByEmailMutation.isPending ? (
                    <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                  ) : (
                    <UserPlus className="mr-2 h-4 w-4" />
                  )}
                  Ajouter l'adresse
                </Button>
              </div>

              <div className="grid gap-3 md:grid-cols-[minmax(0,1fr)_auto] md:items-end">
                <div className="space-y-2">
                  <Label htmlFor="delegated-signer">Ajouter une personne déjà interne</Label>
                  <Select value={candidateUserId} onValueChange={setCandidateUserId}>
                    <SelectTrigger id="delegated-signer">
                      <SelectValue placeholder="Choisir une personne, y compris l’Accueil" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="none">Choisir une personne</SelectItem>
                      {availableCandidates.map((candidate) => (
                        <SelectItem key={candidate.id} value={String(candidate.id)}>
                          {candidate.name} · {candidate.email || "sans email"} · {candidate.role}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
                <Button
                  variant="secondary"
                  onClick={handleAddExistingDelegate}
                  disabled={candidateUserId === "none" || setDelegationMutation.isPending}
                >
                  {setDelegationMutation.isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                  Ajouter
                </Button>
              </div>

              <Separator />

              <div className="space-y-3">
                <Label>Signataires remplaçants actifs</Label>
                {delegatedUsers.length === 0 ? (
                  <p className="text-sm text-muted-foreground">
                    Aucune délégation active pour le moment.
                  </p>
                ) : (
                  <div className="space-y-2">
                    {delegatedUsers.map((entry) => (
                      <div key={entry.id} className="flex flex-col gap-3 rounded-lg border px-4 py-3 md:flex-row md:items-center md:justify-between">
                        <div>
                          <div className="flex flex-wrap items-center gap-2">
                            <p className="font-medium">{entry.name}</p>
                            <Badge variant="outline" className="bg-primary/5 text-primary border-primary/20">
                              Peut signer à ma place
                            </Badge>
                          </div>
                          <p className="text-sm text-muted-foreground">
                            {entry.email || "Sans email"} · {entry.role}
                          </p>
                        </div>
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => handleRemoveDelegate(entry.id)}
                          disabled={removeDelegateMutation.isPending}
                        >
                          {removeDelegateMutation.isPending ? (
                            <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                          ) : (
                            <X className="mr-2 h-4 w-4" />
                          )}
                          Retirer
                        </Button>
                      </div>
                    ))}
                  </div>
                )}
              </div>
            </CardContent>
          </Card>
        )}

        {user.role !== "directrice" && Boolean(user.canSignSalle) && (
          <Card>
            <CardHeader>
              <CardTitle>Signature déléguée active</CardTitle>
              <CardDescription>
                Tu peux signer les demandes de salle au nom de la Directrice tant que cette délégation reste active.
              </CardDescription>
            </CardHeader>
          </Card>
        )}

        <Card id="signature-queue">
          <CardHeader>
            <CardTitle>À signer maintenant</CardTitle>
            <CardDescription>
              Chaque dossier ici a déjà été validé par l’association et transmis par l’hôtesse.
            </CardDescription>
          </CardHeader>
          <CardContent>
            {isLoading ? (
              <div className="flex justify-center py-12">
                <Loader2 className="h-6 w-6 animate-spin" />
              </div>
            ) : normalizedQueue.length === 0 ? (
              <div className="rounded-lg border border-dashed px-6 py-10 text-center text-sm text-muted-foreground">
                Aucun dossier salle n’attend de signature pour le moment.
              </div>
            ) : (
              <div className="space-y-4">
                {normalizedQueue.map((entry) => (
                  <div key={entry.id} className="rounded-lg border p-4">
                    <div className="flex flex-col gap-3 md:flex-row md:items-start md:justify-between">
                      <div className="space-y-2">
                        <div className="flex flex-wrap items-center gap-2">
                          <h3 className="font-semibold">{entry.titre}</h3>
                          <Badge className="border border-amber-200 bg-amber-100 text-amber-900">
                            Signature attendue
                          </Badge>
                        </div>
                        <p className="text-sm text-muted-foreground">{entry.associationName}</p>
                        <div className="grid gap-2 text-sm md:grid-cols-3">
                          <div className="rounded-md border bg-white px-3 py-2">
                            <p className="text-[11px] uppercase tracking-wide text-muted-foreground">Période</p>
                            <p className="font-medium">{entry.period}</p>
                          </div>
                          <div className="rounded-md border bg-white px-3 py-2">
                            <p className="text-[11px] uppercase tracking-wide text-muted-foreground">Horaires</p>
                            <p className="font-medium">{entry.schedule || "-"}</p>
                          </div>
                          <div className="rounded-md border bg-white px-3 py-2">
                            <p className="text-[11px] uppercase tracking-wide text-muted-foreground">Espaces</p>
                            <p className="font-medium">
                              {entry.sallesSelectionnees.length > 0 ? entry.sallesSelectionnees.join(", ") : "-"}
                            </p>
                          </div>
                        </div>
                        <div className="flex flex-wrap items-center gap-3 text-sm text-muted-foreground">
                          <span className="inline-flex items-center gap-1">
                            <Calendar className="h-3.5 w-3.5" />
                            Transmis le {formatDateTime(entry.directorTransmissionAt)}
                          </span>
                          <span>Montant: {formatCurrency(entry.pricing?.totalAmountCents)}</span>
                          {entry.financialMode === "location_payante" && entry.paymentStatus ? (
                            <Badge className={paymentStatusClasses[entry.paymentStatus as SalleWorkflowPaymentStatus]}>
                              {SALLE_WORKFLOW_PAYMENT_STATUS_LABELS[entry.paymentStatus as SalleWorkflowPaymentStatus]}
                            </Badge>
                          ) : null}
                          {entry.financialMode === "location_payante" && entry.paymentDueDate ? (
                            <span>
                              Paiement attendu avant le {formatDate(entry.paymentDueDate)}
                            </span>
                          ) : null}
                        </div>
                        {entry.paymentLate ? (
                          <div className="rounded-md border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-800">
                            Paiement non validé avant la date prévue d’utilisation des lieux.
                          </div>
                        ) : null}
                      </div>
                    <div className="flex flex-col gap-2 md:min-w-[240px]">
                      <Button
                          onClick={() => finalizeSalleReservationMutation.mutate({ id: entry.id })}
                          disabled={finalizeSalleReservationMutation.isPending}
                        >
                          {finalizeSalleReservationMutation.isPending ? (
                            <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                          ) : (
                            <CheckCircle className="mr-2 h-4 w-4" />
                          )}
                          Signer et valider
                        </Button>
                        <div className="space-y-2 rounded-lg border bg-slate-50 p-3">
                          <Label htmlFor={`return-comment-${entry.id}`} className="text-xs text-muted-foreground">
                            Commentaire de retour à l’accueil
                          </Label>
                          <Textarea
                            id={`return-comment-${entry.id}`}
                            placeholder="Explique ici ce que l’hôtesse doit corriger avant une nouvelle transmission."
                            value={returnComments[entry.id] || ""}
                            onChange={(event) => setReturnComments((prev) => ({ ...prev, [entry.id]: event.target.value }))}
                            rows={3}
                          />
                        </div>
                        <Button
                          variant="outline"
                          onClick={() => returnSalleToHostessMutation.mutate({ id: entry.id, comment: returnComments[entry.id] || undefined })}
                          disabled={returnSalleToHostessMutation.isPending}
                        >
                          {returnSalleToHostessMutation.isPending ? (
                            <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                          ) : (
                            <RotateCcw className="mr-2 h-4 w-4" />
                          )}
                          Refuser / Retour à l’accueil
                        </Button>
                        <div className="flex flex-col gap-2 pt-2">
                          {entry.quotePdfUrl ? (
                            <Link href={`/dashboard/requests/${entry.id}/salle-document/devis?returnTo=${encodeURIComponent("/admin")}`}>
                              <Button variant="ghost" className="w-full justify-start">
                                <FileText className="mr-2 h-4 w-4" />
                                Voir le devis
                              </Button>
                            </Link>
                          ) : null}
                          {entry.administrativeDecisionPdfUrl ? (
                            <Link href={`/dashboard/requests/${entry.id}/salle-document/decision?returnTo=${encodeURIComponent("/admin")}`}>
                              <Button variant="ghost" className="w-full justify-start">
                                <FileText className="mr-2 h-4 w-4" />
                                Voir la décision
                              </Button>
                            </Link>
                          ) : null}
                          <Link href={`/dashboard/requests/${entry.id}`}>
                            <Button variant="ghost" className="w-full justify-start">
                              <FileText className="mr-2 h-4 w-4" />
                              Ouvrir le dossier
                            </Button>
                          </Link>
                        </div>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </CardContent>
        </Card>

        <Card id="facturation">
          <CardHeader>
            <CardTitle>Facturation des locations</CardTitle>
            <CardDescription>
              Vue de contrôle pour vérifier si les associations ont réglé leur location avant l’utilisation des lieux.
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="flex flex-wrap gap-2">
              <Badge variant="outline">Toutes : {billingCounts.all}</Badge>
              <Badge className="border-amber-200 bg-amber-100 text-amber-900">En attente : {billingCounts.en_attente}</Badge>
              <Badge variant="destructive">En retard : {billingCounts.en_retard}</Badge>
              <Badge className="border-sky-200 bg-sky-100 text-sky-900">Reçues : {billingCounts.recues}</Badge>
              <Badge className="border-emerald-200 bg-emerald-100 text-emerald-900">Validées : {billingCounts.validees}</Badge>
            </div>

            {billingEntriesLoading ? (
              <div className="flex justify-center py-10">
                <Loader2 className="h-6 w-6 animate-spin" />
              </div>
            ) : !billingEntries?.length ? (
              <div className="rounded-lg border border-dashed px-6 py-10 text-center text-sm text-muted-foreground">
                Aucune location payante à suivre pour le moment.
              </div>
            ) : (
              <div className="space-y-3">
                {billingEntries.map((entry) => (
                  <div key={entry.id} className="flex flex-col gap-3 rounded-lg border px-4 py-4 md:flex-row md:items-start md:justify-between">
                    <div className="space-y-2">
                      <div className="flex flex-wrap items-center gap-2">
                        <h3 className="font-medium">{entry.titre}</h3>
                        <Badge className={paymentStatusClasses[entry.paymentStatus as SalleWorkflowPaymentStatus]}>
                          {SALLE_WORKFLOW_PAYMENT_STATUS_LABELS[entry.paymentStatus as SalleWorkflowPaymentStatus]}
                        </Badge>
                        {entry.isLate ? <Badge variant="destructive">Retard</Badge> : null}
                      </div>
                      <p className="text-sm text-muted-foreground">{entry.associationName}</p>
                      <div className="grid gap-2 text-sm text-muted-foreground md:grid-cols-3">
                        <div>
                          <span className="font-medium text-foreground">Montant dû :</span> {formatCurrency(entry.amountDueCents)}
                        </div>
                        <div>
                          <span className="font-medium text-foreground">Montant reçu :</span> {formatCurrency(entry.amountReceivedCents)}
                        </div>
                        <div>
                          <span className="font-medium text-foreground">Paiement attendu avant :</span> {formatDate(entry.paymentDueDate)}
                        </div>
                        <div>
                          <span className="font-medium text-foreground">Paiement reçu le :</span> {formatDate(entry.paymentReceivedAt)}
                        </div>
                        <div>
                          <span className="font-medium text-foreground">Paiement validé le :</span> {formatDate(entry.paymentValidatedAt)}
                        </div>
                        <div>
                          <span className="font-medium text-foreground">Usage :</span>{" "}
                          {entry.dateReservation
                            ? formatReservationSallePeriod({
                                dateReservation: entry.dateReservation,
                                dateFinReservation: entry.dateFinReservation,
                              })
                            : "-"}
                        </div>
                      </div>
                      {entry.sallesSelectionnees?.length ? (
                        <p className="text-sm text-muted-foreground">
                          Espaces : {entry.sallesSelectionnees.join(", ")}
                        </p>
                      ) : null}
                    </div>
                    <div className="flex items-center gap-2">
                      <Link href={`/dashboard/requests/${entry.id}`}>
                        <Button variant="outline" size="sm">
                          <FileText className="mr-2 h-4 w-4" />
                          Ouvrir le dossier
                        </Button>
                      </Link>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>Calendrier des réservations et demandes matérielles</CardTitle>
            <CardDescription>
              La Directrice peut consulter ici les réservations de salle, les demandes de matériel événementiel et leur état d’avancement.
            </CardDescription>
          </CardHeader>
          <CardContent>
            <ReservationCalendar readOnly />
          </CardContent>
        </Card>

        <Card id="history">
          <CardHeader>
            <CardTitle>Historique / dossiers passés</CardTitle>
            <CardDescription>
              Historique récent des demandes déjà traitées, pour garder une vue d’ensemble avant signature ou en cas d’absence.
            </CardDescription>
          </CardHeader>
          <CardContent>
            {pastRequestsLoading ? (
              <div className="flex justify-center py-10">
                <Loader2 className="h-6 w-6 animate-spin" />
              </div>
            ) : !pastRequests?.length ? (
              <div className="rounded-lg border border-dashed px-6 py-10 text-center text-sm text-muted-foreground">
                Aucune demande passée à afficher pour le moment.
              </div>
            ) : (
              <div className="space-y-3">
                {pastRequests.map((request) => (
                  <div key={request.id} className="flex flex-col gap-3 rounded-lg border px-4 py-4 md:flex-row md:items-start md:justify-between">
                    <div className="space-y-2">
                      <div className="flex flex-wrap items-center gap-2">
                        <h3 className="font-medium">{request.titre}</h3>
                        <Badge variant="outline">{requestTypeLabels[request.type] || request.type}</Badge>
                        <Badge className="bg-slate-100 text-slate-800 border border-slate-200">
                          {statusLabels[request.status] || request.status}
                        </Badge>
                      </div>
                      <p className="text-sm text-muted-foreground">{request.associationName}</p>
                      <div className="grid gap-2 text-sm text-muted-foreground md:grid-cols-3">
                        <div>
                          <span className="font-medium text-foreground">Créée le :</span> {formatDate(request.createdAt)}
                        </div>
                        <div>
                          <span className="font-medium text-foreground">Mise à jour :</span> {formatDate(request.updatedAt)}
                        </div>
                        <div>
                          <span className="font-medium text-foreground">Période :</span>{" "}
                          {request.dateReservation
                            ? formatReservationSallePeriod({
                                dateReservation: request.dateReservation,
                                dateFinReservation: request.dateFinReservation,
                              })
                            : "-"}
                        </div>
                      </div>
                      {request.sallesSelectionnees?.length ? (
                        <p className="text-sm text-muted-foreground">
                          Espaces : {request.sallesSelectionnees.join(", ")}
                        </p>
                      ) : null}
                    </div>
                    <div className="flex items-center gap-2">
                      <Link href={`/dashboard/requests/${request.id}`}>
                        <Button variant="outline" size="sm">
                          Ouvrir
                        </Button>
                      </Link>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
