import Link from "next/link";
import { hasModuleAccess } from "@/lib/auth/module-access";
import { requireOnboardedUser } from "@/lib/auth/user";
import { prisma } from "@/lib/prisma";
import { NormativeAnalysisView } from "@/components/app/normative-analysis-view";
import { PageShell } from "@/components/app/page-shell";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";

type CandadosPageProps = {
  searchParams: Promise<Record<string, string | string[] | undefined>>;
};

function getParam(params: Record<string, string | string[] | undefined>, key: string) {
  const value = params[key];
  return Array.isArray(value) ? value[0] ?? "" : (value ?? "");
}

export default async function CandadosPage({ searchParams }: CandadosPageProps) {
  const user = await requireOnboardedUser();
  const hasPaidModulesAccess = await hasModuleAccess(user, 6);

  if (!hasPaidModulesAccess) {
    return (
      <PageShell title="Modulo 6: Candados" description="Acceso restringido al modulo premium.">
        <Card>
          <CardContent className="space-y-3 py-6">
            <h2 className="text-2xl font-semibold text-[#1f2a40]">Acceso restringido</h2>
            <p className="text-sm text-[#64718a]">Necesitas un plan con acceso premium para ingresar al Modulo 6.</p>
            <Link href="/dashboard#modulos">
              <Button>Ver modulos y planes</Button>
            </Link>
          </CardContent>
        </Card>
      </PageShell>
    );
  }

  const resolvedSearchParams = await searchParams;
  const proposalId = getParam(resolvedSearchParams, "proposalId").trim();
  const sourceIdFromQuery = getParam(resolvedSearchParams, "sourceId").trim();

  const linkedProposal = proposalId
    ? await prisma.proposal.findFirst({
        where: {
          id: proposalId,
          userId: user.id,
        },
        select: {
          id: true,
          title: true,
          issuingEntity: true,
          sourceLicitationId: true,
        },
      })
    : null;

  const sourceId = (linkedProposal?.sourceLicitationId ?? sourceIdFromQuery) || null;
  const linkedSource = sourceId
    ? await prisma.licitation.findUnique({
        where: { id: sourceId },
        select: {
          id: true,
          title: true,
          supplierAwarded: true,
        },
      })
    : null;

  const backHref = linkedProposal ? `/gestion-licitaciones/${encodeURIComponent(linkedProposal.id)}` : "/gestion-licitaciones";

  return (
    <PageShell
      title="Modulo 6: Candados"
      headerMode="module"
      headerBackHref={backHref}
      headerBackLabel="Volver a M5"
      headerNextHref="/compliance-alerts"
      headerNextLabel="M7: Cumplimiento"
      headerShowManual
      headerPlanBadgeLabel="Plan Premium"
      showPageHeading={false}
      contentWidth="wide"
      className="space-y-6"
    >
      <section className="flex items-start gap-4">
        <span className="inline-flex h-14 w-14 items-center justify-center rounded-2xl bg-[#dce5f2] text-3xl text-[#274676]">◨</span>
        <div>
          <h1 className="text-4xl font-semibold text-[#132549] [font-family:var(--font-display)] md:text-5xl">Detector de Candados y Riesgos</h1>
          <p className="mt-2 text-xl text-[#4f6588] md:text-2xl">Modulo 6: detecta direccionamiento, favoritismo y candados en bases de licitacion</p>
        </div>
      </section>

      <NormativeAnalysisView
        linkedProposal={
          linkedProposal
            ? {
                id: linkedProposal.id,
                title: linkedProposal.title,
                issuingEntity: linkedProposal.issuingEntity,
              }
            : null
        }
        linkedSource={
          linkedSource
            ? {
                id: linkedSource.id,
                title: linkedSource.title,
                issuingEntity: linkedSource.supplierAwarded,
              }
            : null
        }
        autoAnalyzeOnLoad={Boolean(linkedProposal || linkedSource)}
        moduleContext="candados"
      />
    </PageShell>
  );
}
