import { SignaturePad, type SignaturePadHandle } from "@/components/SignaturePad";
import { Badge } from "@/components/ui/badge";
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 { buildMaterialReturnFinalPdfViewerHref } from "@/lib/materialReturnFinalPdf";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { trpc } from "@/lib/trpc";
import { AlertCircle, ArrowLeft, CheckCircle2, Download, Loader2, MapPin, Send } from "lucide-react";
import { useEffect, useMemo, useRef, useState } from "react";
import { Link, useLocation, useParams } from "wouter";
import { toast } from "sonner";

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

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

function getReturnHref(role?: string | null) {
  return role === "service_terrain" ? "/terrain" : "/admin?tab=logistique";
}

function getReturnLabel(role?: string | null) {
  return role === "service_terrain" ? "Retour à mes missions" : "Retour à l'administration";
}

const statusLabels: Record<string, string> = {
  planifie: "Planifié",
  en_attente: "En attente",
  en_cours: "En cours / Alerte délai",
  cloture: "Clôturé / Récupéré",
};

const statusClasses: Record<string, string> = {
  planifie: "bg-slate-100 text-slate-700 border-slate-200",
  en_attente: "bg-red-100 text-red-700 border-red-200",
  en_cours: "bg-amber-100 text-amber-700 border-amber-200",
  cloture: "bg-green-100 text-green-700 border-green-200",
};

type FormState = {
  agentName: string;
  agentEmail: string;
  agentRole: string;
  borrowerName: string;
  borrowerRole: string;
  compliance: "conforme" | "non_conforme";
  discrepancyCategories: string[];
  discrepancyDetails: string;
  agentSignatureData: string;
  borrowerSignatureData: string;
};

export default function MaterialReturnUpload() {
  const params = useParams<{ token: string }>();
  const [location] = useLocation();
  const token = params.token || "";
  const searchParams = useMemo(() => {
    const queryIndex = location.indexOf("?");
    return new URLSearchParams(queryIndex >= 0 ? location.slice(queryIndex + 1) : "");
  }, [location]);
  const agentSignatureRef = useRef<SignaturePadHandle>(null);
  const borrowerSignatureRef = useRef<SignaturePadHandle>(null);
  const [geoState, setGeoState] = useState<{
    status: "idle" | "locating" | "available" | "unavailable";
    latitude?: string;
    longitude?: string;
    reason?: string;
    loading: boolean;
  }>({ status: "idle", loading: false });
  const [form, setForm] = useState<FormState>({
    agentName: "",
    agentEmail: "",
    agentRole: "Agent technique",
    borrowerName: "",
    borrowerRole: "Président d'association",
    compliance: "conforme",
    discrepancyCategories: [],
    discrepancyDetails: "",
    agentSignatureData: "",
    borrowerSignatureData: "",
  });

  const { data, isLoading, refetch } = trpc.materialReturn.getPublic.useQuery(
    { token },
    { enabled: Boolean(token) }
  );

  useEffect(() => {
    if (!data) return;
    setForm((prev) => ({
      ...prev,
      agentName: prev.agentName || data.uploadedByName || data.currentUser?.name || "",
      agentEmail: prev.agentEmail || data.uploadedByEmail || data.currentUser?.email || "",
      agentRole: (data.optionSets.agentRoles as readonly string[]).includes(prev.agentRole)
        ? prev.agentRole
        : data.optionSets.agentRoles[0],
      borrowerName: prev.borrowerName || data.borrowerName || data.association?.nomAssociation || "",
      borrowerRole: prev.borrowerRole || data.borrowerRole || "Président d'association",
      compliance: data.compliance || prev.compliance,
      discrepancyCategories: prev.discrepancyCategories.length > 0 ? prev.discrepancyCategories : (data.discrepancyCategories || []),
      discrepancyDetails: prev.discrepancyDetails || data.discrepancyDetails || "",
    }));
  }, [data]);

  useEffect(() => {
    if (!data || data.status === "cloture" || !data.canUpload) return;
    if (geoState.status !== "idle" || geoState.loading) return;
    requestGeolocation(true);
  }, [data, geoState.status, geoState.loading]);

  const completeMutation = trpc.materialReturn.complete.useMutation({
    onSuccess: async (payload) => {
      toast.success(payload.issueFlag ? "Restitution validée avec réserves" : "Restitution validée");
      await refetch();
    },
    onError: (error) => {
      toast.error(error.message || "La validation de la restitution a échoué");
    },
  });

  const downloadPdfMutation = trpc.materialReturn.generatePdf.useMutation({
    onSuccess: (payload) => {
      const viewerHref = buildMaterialReturnFinalPdfViewerHref({
        url: payload.url,
        returnTo: location,
        title: "Consulter la fiche préremplie",
        downloadName: payload.fileName || `fiche-pre-remplie-${data?.requestId || token}.pdf`,
      });
      window.location.href = viewerHref;
    },
    onError: (error) => {
      toast.error(error.message || "Impossible de générer la fiche");
    },
  });

  const selectedDiscrepancyLabels = useMemo(() => {
    if (!data) return [];
    const labels = new Map<string, string>(data.optionSets.discrepancyCategories.map((entry) => [entry.value, entry.label]));
    const selectedValues = data.status === "cloture" ? (data.discrepancyCategories || []) : form.discrepancyCategories;
    return selectedValues.map((value) => labels.get(String(value)) || String(value));
  }, [data, form.discrepancyCategories]);

  const needsDetails = form.compliance === "non_conforme" || form.discrepancyCategories.length > 0;
  const currentUserRole = data?.currentUser?.role;
  const explicitReturnTo = searchParams.get("returnTo") || "";
  const resolvedReturnTo = explicitReturnTo.startsWith("/") ? explicitReturnTo : getReturnHref(currentUserRole);

  const requestGeolocation = (silent = false) => {
    if (!navigator.geolocation) {
      setGeoState({
        status: "unavailable",
        loading: false,
        reason: "Appareil ou navigateur non compatible",
      });
      return;
    }
    setGeoState((prev) => ({ ...prev, status: "locating", loading: true }));
    navigator.geolocation.getCurrentPosition(
      (position) => {
        setGeoState({
          status: "available",
          latitude: String(position.coords.latitude),
          longitude: String(position.coords.longitude),
          loading: false,
          reason: undefined,
        });
      },
      (error) => {
        const reason =
          error.code === error.PERMISSION_DENIED
            ? "Autorisation refusée"
            : error.code === error.TIMEOUT
              ? "Délai dépassé"
              : error.code === error.POSITION_UNAVAILABLE
                ? "Signal faible ou position indisponible"
                : "Signal faible, refus d'autorisation ou GPS indisponible";
        setGeoState({
          status: "unavailable",
          loading: false,
          reason,
        });
        if (!silent) {
          toast.info("Position non disponible, la validation reste possible.");
        }
      },
      { enableHighAccuracy: true, timeout: 5000 }
    );
  };

  const handleToggleCategory = (value: string, checked: boolean) => {
    setForm((prev) => ({
      ...prev,
      discrepancyCategories: checked
        ? Array.from(new Set([...prev.discrepancyCategories, value]))
        : prev.discrepancyCategories.filter((entry) => entry !== value),
    }));
  };

  const handleSubmit = () => {
    if (!data) return;
    if (!form.agentName.trim()) {
      toast.error("Renseigne le nom de l’agent");
      return;
    }
    if (!form.borrowerName.trim()) {
      toast.error("Renseigne le nom du représentant de l’emprunteur");
      return;
    }
    if (needsDetails && !form.discrepancyDetails.trim()) {
      toast.error("Précise les réserves constatées");
      return;
    }
    if (!form.agentSignatureData || agentSignatureRef.current?.isEmpty()) {
      toast.error("La signature de l’agent est obligatoire");
      return;
    }
    if (!form.borrowerSignatureData || borrowerSignatureRef.current?.isEmpty()) {
      toast.error("La signature de l’emprunteur est obligatoire");
      return;
    }

    completeMutation.mutate({
      token,
      agentName: form.agentName.trim(),
      agentEmail: form.agentEmail.trim() || undefined,
      agentRole: form.agentRole as (typeof data.optionSets.agentRoles)[number],
      borrowerName: form.borrowerName.trim(),
      borrowerRole: form.borrowerRole as (typeof data.optionSets.borrowerRoles)[number],
      compliance: form.compliance,
      discrepancyCategories: form.discrepancyCategories as Array<
        | "materiel_manquant"
        | "accessoires_manquants"
        | "structure_deformee"
        | "toile_dechiree"
        | "choc_important"
        | "materiel_sale"
        | "materiel_humide"
      >,
      discrepancyDetails: form.discrepancyDetails.trim() || undefined,
      agentSignatureData: form.agentSignatureData,
      borrowerSignatureData: form.borrowerSignatureData,
      geoLatitude: geoState.latitude,
      geoLongitude: geoState.longitude,
      geoStatus: geoState.status === "available" ? "available" : "unavailable",
      geoFailureReason: geoState.status === "unavailable" ? geoState.reason : undefined,
    });
  };

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

  if (!data) {
    return (
      <div className="min-h-screen bg-muted/30 flex items-center justify-center p-6">
        <Card className="max-w-lg w-full">
          <CardHeader>
            <CardTitle>Lien introuvable</CardTitle>
            <CardDescription>
              Ce lien de restitution n’est plus valide. Il a pu être remplacé après une réactivation ou une relance.
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <p className="text-sm text-muted-foreground">
              Utilise le dernier lien reçu par email, ou contacte l’administration pour qu’elle renvoie un lien actif.
            </p>
            <Link href={resolvedReturnTo}>
              <Button variant="outline" className="gap-2">
                <ArrowLeft className="h-4 w-4" />
                {explicitReturnTo ? "Retour" : getReturnLabel(currentUserRole)}
              </Button>
            </Link>
          </CardContent>
        </Card>
      </div>
    );
  }

  const currentStatusKey = data.status as keyof typeof statusLabels;

  return (
    <div className="min-h-screen bg-muted/30 py-6 md:py-10">
      <main className="container max-w-5xl space-y-6">
        <div className="flex items-center justify-start">
          <Link href={resolvedReturnTo}>
            <Button variant="outline" className="gap-2">
              <ArrowLeft className="h-4 w-4" />
              {explicitReturnTo ? "Retour" : getReturnLabel(currentUserRole)}
            </Button>
          </Link>
        </div>

        <Card className="overflow-hidden border-primary/20">
          <div className="bg-primary text-primary-foreground px-5 py-5 md:px-6">
            <div className="flex flex-wrap items-center gap-3">
              <Badge className={statusClasses[currentStatusKey] || statusClasses.planifie}>
                {statusLabels[currentStatusKey] || data.status}
              </Badge>
              {data.issueFlag ? (
                <Badge variant="outline" className="border-amber-200 bg-amber-100 text-amber-800">
                  Alerte dégradation / litige
                </Badge>
              ) : null}
            </div>
            <h1 className="text-2xl font-bold mt-3">Restitution du matériel événementiel</h1>
            <p className="text-sm opacity-90 mt-1">
              Interface terrain mobile pour constater la restitution, signer et générer la fiche officielle finalisée.
            </p>
          </div>

          <CardContent className="p-5 md:p-6 space-y-6">
            <div className="grid gap-6 lg:grid-cols-[0.95fr_1.05fr]">
              <div className="space-y-4">
                <Card>
                  <CardHeader>
                    <CardTitle className="text-lg">Repères de mission</CardTitle>
                    <CardDescription>
                      Données préremplies issues de la demande validée.
                    </CardDescription>
                  </CardHeader>
                  <CardContent className="space-y-3 text-sm">
                    <div className="flex justify-between gap-3">
                      <span className="text-muted-foreground">Association</span>
                      <span className="font-medium text-right">{data.association?.nomAssociation || "-"}</span>
                    </div>
                    <div className="flex justify-between gap-3">
                      <span className="text-muted-foreground">Commune</span>
                      <span className="font-medium text-right">{data.request.commune || "-"}</span>
                    </div>
                    <div className="flex justify-between gap-3">
                      <span className="text-muted-foreground">Manifestation</span>
                      <span className="font-medium text-right">{data.request.titre}</span>
                    </div>
                    <div className="flex justify-between gap-3">
                      <span className="text-muted-foreground">Période</span>
                      <span className="font-medium text-right">
                        {formatDateFr(data.request.manifestationStart)}
                        {data.request.manifestationEnd && data.request.manifestationEnd !== data.request.manifestationStart
                          ? ` au ${formatDateFr(data.request.manifestationEnd)}`
                          : ""}
                      </span>
                    </div>
                    <div className="flex justify-between gap-3">
                      <span className="text-muted-foreground">Restitution prévue</span>
                      <span className="font-medium text-right">{formatDateFr(data.restitutionDate)}</span>
                    </div>
                    <div className="flex justify-between gap-3">
                      <span className="text-muted-foreground">Validation possible jusqu’au</span>
                      <span className="font-medium text-right">{data.uploadDeadlineLabel}</span>
                    </div>
                    <div className="pt-2">
                      <Button
                        variant="outline"
                        className="w-full"
                        onClick={() => downloadPdfMutation.mutate({ token })}
                        disabled={downloadPdfMutation.isPending}
                      >
                        {downloadPdfMutation.isPending ? (
                          <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                        ) : (
                          <Download className="mr-2 h-4 w-4" />
                        )}
                        Télécharger la fiche préremplie
                      </Button>
                    </div>
                  </CardContent>
                </Card>

                <Card>
                  <CardHeader>
                    <CardTitle className="text-lg">Mise à disposition préremplie</CardTitle>
                    <CardDescription>
                      Matériel attendu au retour.
                    </CardDescription>
                  </CardHeader>
                  <CardContent className="space-y-3">
                    {data.request.requestedItems.length > 0 ? (
                      data.request.requestedItems.map((item) => (
                        <div key={item.key} className="rounded-lg border bg-muted/20 p-3">
                          <div className="flex items-start justify-between gap-3">
                            <div>
                              <p className="font-medium">{item.label}</p>
                              {item.extra ? (
                                <p className="text-sm text-muted-foreground mt-1">{item.extra}</p>
                              ) : null}
                            </div>
                            <Badge variant="outline">Qté {item.quantity || "-"}</Badge>
                          </div>
                        </div>
                      ))
                    ) : (
                      <p className="text-sm text-muted-foreground">Aucun matériel renseigné dans la demande.</p>
                    )}
                  </CardContent>
                </Card>

                {data.status === "cloture" ? (
                  <Card className="border-green-200 bg-green-50">
                    <CardHeader>
                      <CardTitle className="text-lg flex items-center gap-2">
                        <CheckCircle2 className="h-5 w-5 text-green-700" />
                        Restitution déjà finalisée
                      </CardTitle>
                      <CardDescription>
                        Validation enregistrée le {formatDateTimeFr(data.validatedAt || data.uploadedAt)}
                      </CardDescription>
                    </CardHeader>
                    <CardContent className="space-y-3 text-sm">
                      <p>
                        Résultat :{" "}
                        <span className="font-semibold">
                          {data.compliance === "non_conforme" ? "Non conforme / partielle" : "Conforme"}
                        </span>
                      </p>
                      {data.discrepancyCategories?.length ? (
                        <p className="text-muted-foreground">{selectedDiscrepancyLabels.join(" • ")}</p>
                      ) : null}
                      {data.finalPdfUrl ? (
                        <a
                          href={buildMaterialReturnFinalPdfViewerHref({
                            url: data.finalPdfUrl,
                            returnTo: resolvedReturnTo,
                            title: "Consulter le PDF final de restitution",
                            downloadName: `fiche-finale-restitution-${data.requestId || token}.pdf`,
                          })}
                        >
                          <Button variant="outline">
                            <Download className="mr-2 h-4 w-4" />
                            Télécharger le PDF final
                          </Button>
                        </a>
                      ) : null}
                    </CardContent>
                  </Card>
                ) : null}
              </div>

              <div className="space-y-4">
                {!data.canUpload ? (
                  <Card className="border-amber-200 bg-amber-50">
                    <CardContent className="p-5 text-sm text-amber-900">
                      <div className="flex items-center gap-2 font-medium">
                        <AlertCircle className="h-4 w-4" />
                        Validation indisponible
                      </div>
                      <p className="mt-2">
                        Le délai de validation est dépassé. Contacte l’administration pour réactiver le lien ou en recevoir un nouveau.
                      </p>
                    </CardContent>
                  </Card>
                ) : data.status !== "cloture" ? (
                  <>
                    <Card>
                      <CardHeader>
                        <CardTitle className="text-lg">1. Constat de restitution</CardTitle>
                        <CardDescription>
                          Sélectionne un seul résultat global, puis précise les réserves si besoin.
                        </CardDescription>
                      </CardHeader>
                      <CardContent className="space-y-4">
                        <div className="grid gap-3 sm:grid-cols-2">
                          <button
                            type="button"
                            className={`rounded-lg border p-4 text-left transition-colors ${
                              form.compliance === "conforme"
                                ? "border-green-500 bg-green-50"
                                : "border-border bg-white hover:border-green-300"
                            }`}
                            onClick={() => setForm((prev) => ({ ...prev, compliance: "conforme" }))}
                          >
                            <p className="font-semibold text-green-800">Conforme</p>
                            <p className="text-sm text-muted-foreground mt-1">
                              Tout le matériel mis à disposition a été restitué en totalité.
                            </p>
                          </button>
                          <button
                            type="button"
                            className={`rounded-lg border p-4 text-left transition-colors ${
                              form.compliance === "non_conforme"
                                ? "border-amber-500 bg-amber-50"
                                : "border-border bg-white hover:border-amber-300"
                            }`}
                            onClick={() => setForm((prev) => ({ ...prev, compliance: "non_conforme" }))}
                          >
                            <p className="font-semibold text-amber-900">Non conforme / partiel</p>
                            <p className="text-sm text-muted-foreground mt-1">
                              Déverrouille obligatoirement le bloc observations.
                            </p>
                          </button>
                        </div>

                        <div className="rounded-lg border p-4 space-y-3">
                          <p className="font-medium">Observations contradictoires</p>
                          <div className="grid gap-3 sm:grid-cols-2">
                            {data.optionSets.discrepancyCategories.map((option) => (
                              <label key={option.value} className="flex items-start gap-3 rounded-lg border p-3 cursor-pointer bg-white">
                                <Checkbox
                                  checked={form.discrepancyCategories.includes(option.value)}
                                  onCheckedChange={(checked) => handleToggleCategory(option.value, Boolean(checked))}
                                />
                                <span className="text-sm leading-6">{option.label}</span>
                              </label>
                            ))}
                          </div>
                          <div className="space-y-2">
                            <Label htmlFor="discrepancyDetails">
                              Précisions sur les réserves constatées {needsDetails ? "*" : ""}
                            </Label>
                            <Textarea
                              id="discrepancyDetails"
                              value={form.discrepancyDetails}
                              onChange={(event) => setForm((prev) => ({ ...prev, discrepancyDetails: event.target.value }))}
                              placeholder="Décrire précisément les réserves, dégradations ou manques constatés."
                              rows={5}
                            />
                          </div>
                        </div>
                      </CardContent>
                    </Card>

                    <Card>
                      <CardHeader>
                        <CardTitle className="text-lg">2. Signatures et identités</CardTitle>
                        <CardDescription>
                          Ces informations seront figées au moment de la validation finale.
                        </CardDescription>
                      </CardHeader>
                      <CardContent className="space-y-6">
                        <div className="grid gap-4 md:grid-cols-2">
                          <div className="space-y-4">
                            <div className="space-y-2">
                              <Label htmlFor="agentName">Nom / prénom de l’agent CCDS</Label>
                              <Input
                                id="agentName"
                                value={form.agentName}
                                onChange={(event) => setForm((prev) => ({ ...prev, agentName: event.target.value }))}
                              />
                            </div>
                            <div className="space-y-2">
                              <Label htmlFor="agentEmail">Email de l’agent</Label>
                              <Input
                                id="agentEmail"
                                type="email"
                                value={form.agentEmail}
                                onChange={(event) => setForm((prev) => ({ ...prev, agentEmail: event.target.value }))}
                              />
                            </div>
                            <div className="space-y-2">
                              <Label htmlFor="agentRole">Qualité</Label>
                              <select
                                id="agentRole"
                                className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
                                value={form.agentRole}
                                onChange={(event) => setForm((prev) => ({ ...prev, agentRole: event.target.value }))}
                              >
                                {data.optionSets.agentRoles.map((role) => (
                                  <option key={role} value={role}>
                                    {role}
                                  </option>
                                ))}
                              </select>
                            </div>
                            <SignaturePad
                              ref={agentSignatureRef}
                              label="Signature de l’agent"
                              onChange={(value) => setForm((prev) => ({ ...prev, agentSignatureData: value }))}
                            />
                          </div>

                          <div className="space-y-4">
                            <div className="space-y-2">
                              <Label htmlFor="borrowerName">Nom / prénom de l’emprunteur</Label>
                              <Input
                                id="borrowerName"
                                value={form.borrowerName}
                                onChange={(event) => setForm((prev) => ({ ...prev, borrowerName: event.target.value }))}
                              />
                            </div>
                            <div className="space-y-2">
                              <Label htmlFor="borrowerRole">Qualité</Label>
                              <select
                                id="borrowerRole"
                                className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
                                value={form.borrowerRole}
                                onChange={(event) => setForm((prev) => ({ ...prev, borrowerRole: event.target.value }))}
                              >
                                {data.optionSets.borrowerRoles.map((role) => (
                                  <option key={role} value={role}>
                                    {role}
                                  </option>
                                ))}
                              </select>
                            </div>
                            <SignaturePad
                              ref={borrowerSignatureRef}
                              label="Signature de l’emprunteur"
                              onChange={(value) => setForm((prev) => ({ ...prev, borrowerSignatureData: value }))}
                            />
                          </div>
                        </div>

                        <div className="rounded-lg border bg-muted/20 p-4">
                          <div className="flex flex-wrap items-center justify-between gap-3">
                            <div>
                              <p className="font-medium">Horodatage et géolocalisation</p>
                              <p className="text-sm text-muted-foreground">
                                La date et l’heure seront figées automatiquement lors de la double signature.
                              </p>
                            </div>
                            <Button type="button" variant="outline" onClick={() => requestGeolocation()} disabled={geoState.loading}>
                              {geoState.loading ? (
                                <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                              ) : (
                                <MapPin className="mr-2 h-4 w-4" />
                              )}
                              {geoState.status === "unavailable" ? "Relancer la géolocalisation" : "Géolocaliser (optionnel)"}
                            </Button>
                          </div>
                          <div className="mt-3 text-xs text-muted-foreground space-y-1">
                            <p>La validation sera horodatée avec l’heure du serveur CCDS au moment exact de la signature.</p>
                            {geoState.status === "available" && geoState.latitude && geoState.longitude ? (
                              <p>Position capturée : {geoState.latitude}, {geoState.longitude}</p>
                            ) : geoState.status === "unavailable" ? (
                              <p>Position non disponible ({geoState.reason || "cause non déterminée"}). La validation reste possible sans GPS.</p>
                            ) : geoState.status === "locating" ? (
                              <p>Recherche de la position en cours…</p>
                            ) : (
                              <p>Le GPS reste optionnel. En cas d’échec, la restitution pourra être validée normalement.</p>
                            )}
                          </div>
                        </div>

                        <Button className="w-full h-12 text-base" onClick={handleSubmit} disabled={completeMutation.isPending}>
                          {completeMutation.isPending ? (
                            <Loader2 className="mr-2 h-5 w-5 animate-spin" />
                          ) : (
                            <Send className="mr-2 h-5 w-5" />
                          )}
                          Valider la restitution
                        </Button>
                      </CardContent>
                    </Card>
                  </>
                ) : null}
              </div>
            </div>
          </CardContent>
        </Card>
      </main>
    </div>
  );
}
