import { AuthenticatedPageSkeleton } from "@/components/AuthenticatedPageSkeleton";
import { EmptyStateCard } from "@/components/EmptyStateCard";
import { PortalActionGroup, PortalDashboardHeader, PortalSectionIntro, PortalSurface } from "@/components/portal/PortalSurface";
import { useViewportFlags } from "@/hooks/useMobile";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { buildRoutePrefetchHandlers } from "@/lib/routePrefetch";
import { trpc } from "@/lib/trpc";
import { getFriendlyActionError } from "@/lib/userFeedback";
import { cn } from "@/lib/utils";
import { CheckCircle, ClipboardList, Edit, Eye, FileText, Loader2, Plus, XCircle } from "lucide-react";
import { toast } from "sonner";
import { Link } from "wouter";

const statusConfig: Record<string, { label: string; className: string }> = {
  brouillon: { label: 'Brouillon', className: 'bg-gray-100 text-gray-700' },
  soumise: { label: 'Soumise', className: 'bg-blue-100 text-blue-700' },
  en_cours_traitement: { label: 'En cours', className: 'bg-yellow-100 text-yellow-700' },
  information_complementaire: { label: 'Info requise', className: 'bg-orange-100 text-orange-700' },
  validee: { label: 'Validée', className: 'bg-green-100 text-green-700' },
  refusee: { label: 'Refusée', className: 'bg-red-100 text-red-700' },
  annulee: { label: 'Annulée', className: 'bg-gray-100 text-gray-500' },
};

const requestTypeLabels: Record<string, string> = {
  subvention_fonctionnement: 'Subvention de fonctionnement',
  subvention_projet: 'Subvention de projet',
  agrement_jeunesse_education: 'Agrément Jeunesse et Éducation',
  agrement_sport: 'Agrément Sport',
  autorisation_occupation: 'Autorisation d\'occupation',
  demande_salle: 'Demande de salle',
  demande_materiel_evenementiel: 'Demande du matériel événementiel',
  autre: 'Autre',
};

function getSalleWorkflowQuoteStatus(formDataRaw: string | null | undefined): string | null {
  try {
    const formData = formDataRaw ? JSON.parse(formDataRaw) : {};
    return typeof formData?.salleWorkflow?.quoteStatus === "string" ? formData.salleWorkflow.quoteStatus : null;
  } catch {
    return null;
  }
}

function getSalleWorkflowLockState(formDataRaw: string | null | undefined) {
  try {
    const formData = formDataRaw ? JSON.parse(formDataRaw) : {};
    const workflow = formData?.salleWorkflow;
    return {
      directorStatus: typeof workflow?.directorStatus === "string" ? workflow.directorStatus : null,
      finalNotificationSentAt:
        typeof workflow?.finalNotificationSentAt === "string" ? workflow.finalNotificationSentAt : null,
    };
  } catch {
    return {
      directorStatus: null,
      finalNotificationSentAt: null,
    };
  }
}

function getRequestStatusMeta(request: { status: string; type: string; formData?: string | null }) {
  const defaultStatus = statusConfig[request.status] || {
    label: request.status,
    className: 'bg-gray-100 text-gray-700',
  };

  if (request.type !== 'demande_salle') {
    return defaultStatus;
  }

  const quoteStatus = getSalleWorkflowQuoteStatus(request.formData);
  if (quoteStatus === 'en_attente_association') {
    return {
      label: "En attente de réponse de l'association",
      className: 'bg-violet-100 text-violet-700',
    };
  }

  return defaultStatus;
}

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

export default function Requests() {
  const { isMobile, isTablet } = useViewportFlags();
  const { data: requests, isLoading } = trpc.request.getMyRequests.useQuery();
  const utils = trpc.useUtils();
  const isCompactViewport = isMobile || isTablet;

  const respondSalleQuoteMutation = trpc.request.respondSalleQuote.useMutation({
    onSuccess: (data) => {
      const accepted = data.quoteStatus === "accepte";
      utils.request.getMyRequests.invalidate();
      toast.success(
        accepted
          ? "Votre accord a bien été enregistré. Le dossier repart vers l’hôtesse."
          : "Votre refus a bien été enregistré."
      );
    },
    onError: (error) => {
      toast.error(
        getFriendlyActionError(
          error,
          "Impossible d'enregistrer votre réponse pour le moment. Vérifiez votre session puis réessayez."
        )
      );
    },
  });

  const formatDate = (date: Date | string | null) => {
    if (!date) return '-';
    return new Date(date).toLocaleDateString('fr-FR', {
      day: '2-digit',
      month: '2-digit',
      year: 'numeric',
    });
  };

  const formatAmount = (cents: number | null) => {
    if (!cents) return '-';
    return new Intl.NumberFormat('fr-FR', { style: 'currency', currency: 'EUR' }).format(cents / 100);
  };

  const filterRequests = (status: string | null) => {
    if (!requests) return [];
    if (!status) return requests;
    if (status === 'en_cours') {
      return requests.filter(r => ['soumise', 'en_cours_traitement', 'information_complementaire'].includes(r.status));
    }
    if (status === 'terminee') {
      return requests.filter(r => ['validee', 'refusee'].includes(r.status));
    }
    return requests.filter(r => r.status === status);
  };

  const requestTabs = [
    { value: "all", label: "Toutes", count: requests?.length ?? 0 },
    { value: "brouillon", label: "Brouillons", count: filterRequests("brouillon").length },
    { value: "en_cours", label: "En cours", count: filterRequests("en_cours").length },
    { value: "terminee", label: "Terminées", count: filterRequests("terminee").length },
  ];

  return (
    <div className="portal-immersive-page min-h-screen">
      <PortalDashboardHeader
        tourId="requests-header"
        title="Mes demandes"
        description={`${requests?.length || 0} demande(s) suivie(s) dans votre espace association.`}
        actions={
          <Link href="/dashboard/requests/new" className="w-full sm:w-auto" {...buildRoutePrefetchHandlers("/dashboard/requests/new")}>
            <Button data-tour-id="requests-new" className="min-h-11 w-full sm:w-auto">
              <Plus className="mr-2 h-4 w-4" />
              Nouvelle demande
            </Button>
          </Link>
        }
      />

      <main className="container py-5 sm:py-8">
        {isLoading ? (
          <div className="mx-auto max-w-5xl">
            <AuthenticatedPageSkeleton
              hero={false}
              message="Chargement de vos demandes, de leur statut et des réponses attendues..."
              cards={2}
              formRows={3}
            />
          </div>
        ) : requests && requests.length > 0 ? (
          <Tabs defaultValue="all" className="space-y-6">
            <PortalSurface
              className="border-primary/10 bg-gradient-to-r from-primary/10 via-white to-primary/5"
              bodyClassName="space-y-4"
            >
              <PortalSectionIntro
                eyebrow="Suivi"
                title="Retrouvez vos dossiers selon leur état"
                description="Brouillons, demandes en cours, validations et dossiers terminés restent accessibles ici avec un suivi plus clair."
                aside="Changez de vue selon l’étape de traitement qui vous intéresse."
              />
              <TabsList className="flex w-full justify-start gap-1.5 overflow-x-auto rounded-2xl border border-border/70 bg-white/90 p-1 pr-3 shadow-[0_12px_28px_-24px_rgba(15,23,42,0.18)] snap-x snap-mandatory [scrollbar-width:none] [-ms-overflow-style:none] [&::-webkit-scrollbar]:hidden sm:gap-2 sm:p-1.5">
                {requestTabs.map((tabItem) => (
                  <TabsTrigger
                    key={tabItem.value}
                    value={tabItem.value}
                    className="h-auto min-h-10 flex-none snap-start rounded-xl px-3 py-2 text-[13px] font-semibold sm:min-h-11 sm:px-4 sm:text-sm"
                  >
                    <span>{tabItem.label}</span>
                    <span className="rounded-full bg-slate-100 px-1.5 py-0.5 text-[11px] font-semibold leading-none text-slate-600 sm:px-2 sm:text-xs">
                      {tabItem.count}
                    </span>
                  </TabsTrigger>
                ))}
              </TabsList>
            </PortalSurface>

            {['all', 'brouillon', 'en_cours', 'terminee'].map((tab) => (
              <TabsContent key={tab} value={tab} className="space-y-4">
                {filterRequests(tab === 'all' ? null : tab).map((request) => (
	                  <Card key={request.id} className="overflow-hidden rounded-2xl border border-border/70 bg-white/95 transition-all duration-200 hover:-translate-y-0.5 hover:shadow-md">
	                    <CardContent className="p-4 sm:p-5">
	                      {(() => {
                        const salleQuoteStatus = request.type === "demande_salle"
                          ? getSalleWorkflowQuoteStatus(request.formData)
                          : null;
                        const salleWorkflowDocuments = request.type === "demande_salle"
                          ? getSalleWorkflowDocuments(request.formData)
                          : { quotePdfUrl: "", decisionPdfUrl: "" };
                        const salleWorkflowLockState = request.type === "demande_salle"
                          ? getSalleWorkflowLockState(request.formData)
                          : { directorStatus: null, finalNotificationSentAt: null };
                        const requestStatusMeta = getRequestStatusMeta(request);
                        const needsAssociationResponse = salleQuoteStatus === "en_attente_association";
                        const lockedForFinalization = salleWorkflowLockState.directorStatus === "signee"
                          && !salleWorkflowLockState.finalNotificationSentAt;
                        const canEdit = ['brouillon', 'information_complementaire'].includes(request.status)
                          && !needsAssociationResponse
                          && !lockedForFinalization;

	                        return (
	                          <div className="flex flex-col gap-4 xl:flex-row xl:items-start xl:justify-between">
	                            <div className="flex min-w-0 items-start gap-4 flex-1">
	                              <div className="flex h-11 w-11 shrink-0 items-center justify-center rounded-xl bg-primary/10">
	                                <FileText className="h-6 w-6 text-primary" />
	                              </div>
	                              <div className="flex-1 min-w-0">
	                                <div className="mb-3 rounded-2xl border border-primary/10 bg-gradient-to-r from-primary/10 via-white to-primary/5 p-4">
	                                  <div className="flex flex-wrap items-center gap-2">
	                                    <span className="rounded-full border border-primary/15 bg-white/80 px-2.5 py-1 text-[11px] font-semibold uppercase tracking-[0.14em] text-primary">
	                                      {requestTypeLabels[request.type] || request.type}
	                                    </span>
	                                    <span className={`rounded-full px-2.5 py-1 text-xs font-medium ${requestStatusMeta.className}`}>
	                                      {requestStatusMeta.label}
	                                    </span>
	                                    {needsAssociationResponse && (
	                                      <span className="rounded-full bg-blue-100 px-2.5 py-1 text-xs font-medium text-blue-700">
	                                        Réponse attendue
	                                      </span>
	                                    )}
	                                  </div>
	                                  <h3 className="mt-3 min-w-0 break-words text-base font-semibold leading-6 text-slate-950 sm:text-lg">
	                                    {request.titre}
	                                  </h3>
	                                  <div className="mt-3 grid gap-2 sm:grid-cols-3">
	                                    <div className="rounded-xl border border-white/80 bg-white/90 px-3 py-2.5">
	                                      <p className="text-[11px] uppercase tracking-wide text-muted-foreground">Création</p>
	                                      <p className="mt-1 text-sm font-semibold text-slate-950">{formatDate(request.createdAt)}</p>
	                                    </div>
	                                    <div className="rounded-xl border border-white/80 bg-white/90 px-3 py-2.5">
	                                      <p className="text-[11px] uppercase tracking-wide text-muted-foreground">Soumission</p>
	                                      <p className="mt-1 text-sm font-semibold text-slate-950">{request.dateSubmission ? formatDate(request.dateSubmission) : "En préparation"}</p>
	                                    </div>
	                                    <div className="rounded-xl border border-white/80 bg-white/90 px-3 py-2.5">
	                                      <p className="text-[11px] uppercase tracking-wide text-muted-foreground">Montant</p>
	                                      <p className="mt-1 text-sm font-semibold text-slate-950">{request.montantDemande ? formatAmount(request.montantDemande) : "—"}</p>
	                                    </div>
	                                  </div>
	                                </div>
	                                <div className="flex flex-wrap items-center gap-2.5 text-sm text-muted-foreground">
	                                  <span className="rounded-full bg-slate-100 px-2.5 py-1">Référence #{request.id}</span>
	                                </div>
	                                {request.commentaireAdmin && (
	                                  <div className="mt-3 rounded-xl border border-slate-200 bg-slate-50 px-3 py-3 text-sm leading-6">
                                    <span className="font-medium">Commentaire: </span>
                                    {request.commentaireAdmin}
                                  </div>
                                )}
                                {needsAssociationResponse && (
                                  <div className="mt-4 space-y-4">
                                    <div className="rounded-xl border border-primary/20 bg-primary/5 p-4 text-sm">
                                      <p className="font-medium text-foreground">Avant de répondre</p>
                                      <p className="mt-1 text-muted-foreground">
                                        Consultez d’abord le devis, puis indiquez si vous êtes d’accord avec le tarif proposé.
                                      </p>
                                    </div>
                                    <div className="grid gap-3 sm:grid-cols-2">
                                      {salleWorkflowDocuments.quotePdfUrl && (
                                        <div className="rounded-xl border border-slate-200 bg-white px-4 py-4 shadow-[0_12px_28px_-24px_rgba(15,23,42,0.22)]">
                                          <p className="text-sm font-semibold text-slate-950">Devis</p>
                                          <p className="mt-1 text-sm text-muted-foreground">Consultez le tarif proposé avant de répondre.</p>
                                          <Link href={`/dashboard/requests/${request.id}/salle-document/devis?returnTo=${encodeURIComponent("/dashboard/requests")}`}>
                                            <Button size="sm" variant="outline" className="mt-4 h-10 w-full justify-start sm:justify-center">
                                              <FileText className="mr-2 h-4 w-4" />
                                              Voir le devis
                                            </Button>
                                          </Link>
                                        </div>
                                      )}
                                      {salleWorkflowDocuments.decisionPdfUrl && (
                                        <div className="rounded-xl border border-slate-200 bg-white px-4 py-4 shadow-[0_12px_28px_-24px_rgba(15,23,42,0.22)]">
                                          <p className="text-sm font-semibold text-slate-950">Décision administrative</p>
                                          <p className="mt-1 text-sm text-muted-foreground">Retrouvez la décision transmise avec le dossier.</p>
                                          <Link href={`/dashboard/requests/${request.id}/salle-document/decision?returnTo=${encodeURIComponent("/dashboard/requests")}`}>
                                            <Button size="sm" variant="outline" className="mt-4 h-10 w-full justify-start sm:justify-center">
                                              <Eye className="mr-2 h-4 w-4" />
                                              Voir la décision
                                            </Button>
                                          </Link>
                                        </div>
                                      )}
                                    </div>
                                    <PortalActionGroup className="pt-1">
                                      <Button
                                        size="sm"
                                        className="min-h-11 w-full sm:w-auto"
                                        onClick={() => respondSalleQuoteMutation.mutate({ id: request.id, 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" />
                                        )}
                                        J’accepte le devis
                                      </Button>
                                      <Button
                                        size="sm"
                                        className="min-h-11 w-full sm:w-auto"
                                        variant="destructive"
                                        onClick={() => respondSalleQuoteMutation.mutate({ id: request.id, 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>
                                    </PortalActionGroup>
                                  </div>
                                )}
                              </div>
                            </div>
                            <div className={cn("flex w-full flex-col gap-2 sm:flex-row xl:w-auto xl:flex-col", isCompactViewport && "pt-1")}>
                              <Link href={`/dashboard/requests/${request.id}`} {...buildRoutePrefetchHandlers(`/dashboard/requests/${request.id}`)}>
                                <Button variant="outline" size="sm" className={cn("w-full", isMobile && "min-h-11")}>
                                  <Eye className="mr-2 h-4 w-4" />
                                  {needsAssociationResponse ? 'Répondre' : 'Voir'}
                                </Button>
                              </Link>
                              {canEdit && (
                                <Link href={`/dashboard/requests/${request.id}/edit`} {...buildRoutePrefetchHandlers(`/dashboard/requests/${request.id}/edit`)}>
                                  <Button variant="default" size="sm" className={cn("w-full", isMobile && "min-h-11")}>
                                    <Edit className="mr-2 h-4 w-4" />
                                    Éditer
                                  </Button>
                                </Link>
                              )}
                            </div>
                          </div>
                        );
                      })()}
                    </CardContent>
                  </Card>
                ))}
                {filterRequests(tab === 'all' ? null : tab).length === 0 && (
                  <EmptyStateCard
                    icon={ClipboardList}
                    title="Aucune demande dans cette catégorie"
                    description="Le suivi reste vide pour ce filtre. Vous pouvez revenir à l’ensemble des demandes ou créer un nouveau dossier selon votre besoin."
                    secondaryActionLabel="Voir toutes mes demandes"
                    onSecondaryAction={() => {
                      const allTabButton = document.querySelector('[data-value=\"all\"]') as HTMLButtonElement | null;
                      allTabButton?.click();
                    }}
                    actionLabel="Nouvelle demande"
                    onAction={() => {
                      window.location.href = "/dashboard/requests/new";
                    }}
                  />
                )}
              </TabsContent>
            ))}
          </Tabs>
        ) : (
          <div className="mx-auto max-w-4xl">
            <EmptyStateCard
              icon={ClipboardList}
              title="Vous n’avez pas encore déposé de demande"
              description="Vous pouvez créer une nouvelle demande de salle, de matériel, de subvention ou d’accompagnement depuis votre espace association. Une fois envoyée, elle apparaîtra ici avec son état d’avancement."
              actionLabel="Créer une demande"
              onAction={() => {
                window.location.href = "/dashboard/requests/new";
              }}
            />
          </div>
        )}
      </main>
    </div>
  );
}
