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

function extractSalleWorkflow(formDataRaw: string | null | undefined) {
  try {
    const formData = formDataRaw ? JSON.parse(formDataRaw) : {};
    const workflow = formData?.salleWorkflow;
    if (!workflow || typeof workflow !== "object") {
      return null;
    }
    return {
      quotePdfUrl: typeof workflow.quotePdfUrl === "string" ? workflow.quotePdfUrl : "",
      quotePdfName: typeof workflow.quotePdfName === "string" ? workflow.quotePdfName : "",
      quoteStatus: typeof workflow.quoteStatus === "string" ? workflow.quoteStatus : "",
      administrativeDecisionPdfUrl:
        typeof workflow.administrativeDecisionPdfUrl === "string" ? workflow.administrativeDecisionPdfUrl : "",
      administrativeDecisionPdfName:
        typeof workflow.administrativeDecisionPdfName === "string" ? workflow.administrativeDecisionPdfName : "",
    };
  } catch {
    return null;
  }
}

function getDocumentConfig(documentType: string, workflow: ReturnType<typeof extractSalleWorkflow>) {
  if (documentType === "devis") {
    return {
      title: "Consulter le devis",
      description: "Consulte le devis généré pour ce dossier, puis reviens facilement à la demande.",
      url: workflow?.quotePdfUrl || "",
      fileName: workflow?.quotePdfName || "",
      buttonLabel: "Télécharger le devis",
    };
  }

  return {
    title: "Consulter la décision administrative",
    description: "Consulte la décision administrative générée pour ce dossier, puis reviens facilement à la demande.",
    url: workflow?.administrativeDecisionPdfUrl || "",
    fileName: workflow?.administrativeDecisionPdfName || "",
    buttonLabel: "Télécharger la décision",
  };
}

export default function SalleWorkflowDocumentDownload() {
  const params = useParams<{ id: string; documentType: string }>();
  const [location, setLocation] = useLocation();
  const requestId = Number.parseInt(params.id || "0", 10);
  const documentType = params.documentType === "devis" ? "devis" : "decision";
  const utils = trpc.useUtils();
  const searchParams = useMemo(() => {
    const queryIndex = location.indexOf("?");
    return new URLSearchParams(queryIndex >= 0 ? location.slice(queryIndex + 1) : "");
  }, [location]);
  const rawReturnTo = searchParams.get("returnTo") || "";
  const returnTo = rawReturnTo.startsWith("/") ? rawReturnTo : `/dashboard/requests/${requestId}`;

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

  const respondSalleQuoteMutation = trpc.request.respondSalleQuote.useMutation({
    onSuccess: (data) => {
      utils.request.getMyRequests.invalidate();
      utils.request.getById.invalidate({ id: requestId });
      toast.success(
        data.quoteStatus === "accepte"
          ? "Votre accord a bien été enregistré. Le dossier repart vers l’hôtesse."
          : "Votre refus a bien été enregistré."
      );
      setLocation(returnTo);
    },
    onError: (error) => {
      toast.error(error.message || "Impossible d'enregistrer votre réponse");
    },
  });

  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 workflow = extractSalleWorkflow(request?.formData);
  const document = getDocumentConfig(documentType, workflow);
  const hasDocument = Boolean(document.url && document.fileName);
  const canRespondToQuote = documentType === "devis" && workflow?.quoteStatus === "en_attente_association";

  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={returnTo}>
            <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" />
              {document.title}
            </CardTitle>
            <CardDescription>{document.description}</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 salle"}</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>
            </div>

            {hasDocument ? (
              <div className="space-y-4">
                <div className="flex flex-wrap gap-3">
                  <a href={document.url} target="_blank" rel="noopener noreferrer">
                    <Button variant="outline" className="gap-2">
                      <ExternalLink className="h-4 w-4" />
                      Ouvrir dans un nouvel onglet
                    </Button>
                  </a>
                  <a href={document.url} target="_blank" rel="noopener noreferrer" download={document.fileName}>
                    <Button className="gap-2">
                      <Download className="h-4 w-4" />
                      {document.buttonLabel}
                    </Button>
                  </a>
                  <Link href={returnTo}>
                    <Button variant="outline">Retour à la demande</Button>
                  </Link>
                </div>

                <div className="rounded-lg border bg-white overflow-hidden">
                  <div className="flex flex-col gap-3 border-b bg-muted/20 px-4 py-3 md:flex-row md:items-center md:justify-between">
                    <div>
                      <p className="text-sm font-semibold">Prévisualisation du document</p>
                      <p className="text-xs text-muted-foreground">
                        Le bouton retour reste disponible ici pendant toute la lecture.
                      </p>
                    </div>
                    <Link href={returnTo}>
                      <Button variant="outline" size="sm">
                        <ArrowLeft className="mr-2 h-4 w-4" />
                        Retour
                      </Button>
                    </Link>
                  </div>
                  <iframe
                    src={document.url}
                    title={document.title}
                    className="h-[70vh] w-full bg-white"
                  />
                </div>

                {canRespondToQuote ? (
                  <div className="rounded-lg border border-primary/20 bg-primary/5 p-4 space-y-3">
                    <div>
                      <p className="text-sm font-semibold">Votre réponse est attendue juste après lecture du devis</p>
                      <p className="mt-1 text-sm text-muted-foreground">
                        Si vous êtes d’accord avec le tarif proposé, vous pouvez accepter le devis maintenant. Sinon, vous pouvez le refuser.
                      </p>
                    </div>
                    <div className="flex flex-wrap gap-3">
                      <Button
                        onClick={() => respondSalleQuoteMutation.mutate({ id: requestId, decision: "accepte" })}
                        disabled={respondSalleQuoteMutation.isPending}
                      >
                        {respondSalleQuoteMutation.isPending ? (
                          <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                        ) : (
                          <CheckCircle className="mr-2 h-4 w-4" />
                        )}
                        Je suis d’accord avec le tarif
                      </Button>
                      <Button
                        variant="destructive"
                        onClick={() => respondSalleQuoteMutation.mutate({ id: requestId, decision: "refuse" })}
                        disabled={respondSalleQuoteMutation.isPending}
                      >
                        {respondSalleQuoteMutation.isPending ? (
                          <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                        ) : (
                          <XCircle className="mr-2 h-4 w-4" />
                        )}
                        Je refuse le devis
                      </Button>
                    </div>
                  </div>
                ) : null}

                <div className="flex justify-end">
                  <Link href={returnTo}>
                    <Button variant="outline">
                      <ArrowLeft className="mr-2 h-4 w-4" />
                      Retour à la demande
                    </Button>
                  </Link>
                </div>
              </div>
            ) : (
              <div className="rounded-lg border border-amber-200 bg-amber-50 p-4 text-sm text-amber-900">
                Ce document n’est pas encore disponible pour ce dossier.
              </div>
            )}
          </CardContent>
        </Card>
      </main>
    </div>
  );
}
