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 NormativeAnalysisPageProps = {
  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 NormativeAnalysisPage({ searchParams }: NormativeAnalysisPageProps) {
  const user = await requireOnboardedUser();
  const hasPaidModulesAccess = await hasModuleAccess(user, 4);

  if (!hasPaidModulesAccess) {
    return (
      <PageShell
        title="Modulo 4: Analisis Normativo"
        description="Este modulo esta protegido por suscripcion de pago."
        action={<span className="rounded-full border border-[#d5ddec] bg-[#edf2fb] px-4 py-1 text-sm font-semibold text-[#5a6a87]">Bloqueado</span>}
      >
        <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]">
              El Modulo 4 forma parte de la ruta premium. Tu cuenta actual puede completar el Diagnostico (Modulo 1) y revisar los planes en la seccion Modulos.
            </p>
            <Link href="/dashboard#modulos">
              <Button>Ver modulos y planes</Button>
            </Link>
          </CardContent>
        </Card>
      </PageShell>
    );
  }

  const params = await searchParams;
  const sourceId = getParam(params, "sourceId").trim();
  const linkedSource = sourceId
    ? await prisma.licitation.findUnique({
        where: { id: sourceId },
        select: {
          id: true,
          title: true,
          supplierAwarded: true,
        },
      })
    : null;

  return (
    <PageShell
      title="Modulo 4: Analisis Normativo"
      headerMode="module"
      headerBackHref="/dashboard"
      headerBackLabel="Volver al Dashboard"
      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">Modulo 4: Analisis Normativo</h1>
          <p className="mt-2 text-xl text-[#4f6588] md:text-2xl">Analiza bases de licitacion, reglamentos y leyes con IA</p>
        </div>
      </section>

      <NormativeAnalysisView
        linkedSource={
          linkedSource
            ? {
                id: linkedSource.id,
                title: linkedSource.title,
                issuingEntity: linkedSource.supplierAwarded,
              }
            : null
        }
        autoAnalyzeOnLoad={Boolean(linkedSource)}
      />

      <section className="rounded-2xl border border-[#d8e0ec] bg-[#f4f7fb] px-6 py-5">
        <div className="flex flex-wrap items-center justify-between gap-3">
          <div>
            <p className="text-3xl font-semibold text-[#17315a] [font-family:var(--font-display)]">Navegacion</p>
            <p className="text-lg text-[#5c7395]">Regresa al Modulo 3 para ver mas oportunidades o vuelve al dashboard.</p>
          </div>
          <div className="flex flex-wrap gap-2">
            <Link href="/licitations">
              <Button size="lg" className="rounded-2xl px-6">
                Volver a Oportunidades
              </Button>
            </Link>
            <Link href="/dashboard">
              <Button size="lg" variant="secondary" className="rounded-2xl px-6">
                Ir al Dashboard
              </Button>
            </Link>
          </div>
        </div>
      </section>
    </PageShell>
  );
}
