import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { trpc } from "@/lib/trpc";
import { ArrowLeft, Download, FileText, Loader2 } from "lucide-react";
import { Link, useParams } from "wouter";

function extractMaterialConvention(formDataRaw: string | null | undefined) {
  try {
    const formData = formDataRaw ? JSON.parse(formDataRaw) : {};
    const financialDecision = formData?.cadreDSU?.materielEvent?.financialDecision;
    if (!financialDecision || typeof financialDecision !== "object") {
      return null;
    }
    return {
      contractPdfUrl: typeof financialDecision.contractPdfUrl === "string" ? financialDecision.contractPdfUrl : "",
      contractPdfName: typeof financialDecision.contractPdfName === "string" ? financialDecision.contractPdfName : "",
      financialMode: typeof financialDecision.financialMode === "string" ? financialDecision.financialMode : "",
    };
  } catch {
    return null;
  }
}

function getFinancialModeLabel(mode: string) {
  switch (mode) {
    case "gratuite":
      return "Mise à disposition gratuite";
    case "gratuite_avec_caution":
      return "Mise à disposition gratuite avec caution";
    case "location_payante":
      return "Location payante";
    default:
      return "Mode non renseigné";
  }
}

export default function MaterialConventionDownload() {
  const params = useParams<{ id: string }>();
  const requestId = Number.parseInt(params.id || "0", 10);

  const { data: request, isLoading } = trpc.request.getById.useQuery(
    { id: requestId },
    { enabled: requestId > 0 }
  );

  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>
    );
  }

  const convention = extractMaterialConvention(request?.formData);
  const hasConvention = Boolean(convention?.contractPdfUrl && convention?.contractPdfName);

  return (
    <div className="min-h-screen bg-muted/30 py-8">
      <main className="container max-w-3xl space-y-6">
        <div className="flex items-center justify-start">
          <Link href={`/dashboard/requests/${requestId}`}>
            <Button variant="outline" className="gap-2">
              <ArrowLeft className="h-4 w-4" />
              Retour
            </Button>
          </Link>
        </div>

        <Card className="border-primary/20">
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <FileText className="h-5 w-5 text-primary" />
              Télécharger la convention matériel CCDS
            </CardTitle>
            <CardDescription>
              Reviens directement à la demande ou télécharge la convention générée pour ce dossier.
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="rounded-lg border bg-white p-4 space-y-2">
              <p className="text-sm">
                <span className="text-muted-foreground">Dossier :</span>{" "}
                <span className="font-medium">#{request?.id || requestId}</span>
              </p>
              <p className="text-sm">
                <span className="text-muted-foreground">Demande :</span>{" "}
                <span className="font-medium">{request?.titre || "Demande de matériel"}</span>
              </p>
              <p className="text-sm">
                <span className="text-muted-foreground">Association :</span>{" "}
                <span className="font-medium">{request?.associationInfo?.nomAssociation || "Non renseignée"}</span>
              </p>
              <p className="text-sm">
                <span className="text-muted-foreground">Mode retenu :</span>{" "}
                <span className="font-medium">{getFinancialModeLabel(convention?.financialMode || "")}</span>
              </p>
            </div>

            {hasConvention ? (
              <div className="flex flex-wrap gap-3">
                <a href={convention?.contractPdfUrl} target="_blank" rel="noopener noreferrer" download={convention?.contractPdfName}>
                  <Button className="gap-2">
                    <Download className="h-4 w-4" />
                    Télécharger la convention
                  </Button>
                </a>
                <Link href={`/dashboard/requests/${requestId}`}>
                  <Button variant="outline">
                    Retour à la demande
                  </Button>
                </Link>
              </div>
            ) : (
              <div className="rounded-lg border border-amber-200 bg-amber-50 p-4 text-sm text-amber-900">
                La convention matériel n’est pas encore générée pour ce dossier.
              </div>
            )}
          </CardContent>
        </Card>
      </main>
    </div>
  );
}
