import Link from "next/link";
import { hasModuleAccess } from "@/lib/auth/module-access";
import { requireOnboardedUser } from "@/lib/auth/user";
import {
  getInstitutionalDossierForUser,
  getAuditKpisForUser,
  listAuditSimulationsForUser,
} from "@/lib/audits/server";
import { PreventiveDossierView } from "@/components/app/preventive-dossier-view";
import { PageShell } from "@/components/app/page-shell";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import type { InstitutionalDossierLoadStrategy } from "@/lib/audits/types";

type PageProps = {
  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 ExpedientePreventivoPage({ searchParams }: PageProps) {
  const user = await requireOnboardedUser();
  const hasPaidModulesAccess = await hasModuleAccess(user, 10);

  if (!hasPaidModulesAccess) {
    return (
      <PageShell
        title="Modulo 10: Expediente Preventivo"
        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]">Modulo 10 forma parte de la ruta premium de modulos pagados.</p>
            <div className="flex flex-wrap gap-2">
              <Link href="/dashboard#modulos">
                <Button>Ver modulos y planes</Button>
              </Link>
              <Link href="/proteccion-legal">
                <Button variant="secondary">Ir a Modulo 9</Button>
              </Link>
            </div>
          </CardContent>
        </Card>
      </PageShell>
    );
  }

  const resolvedSearchParams = await searchParams;
  const strategy = (getParam(resolvedSearchParams, "strategy") === "snapshot" ? "snapshot" : "live") satisfies InstitutionalDossierLoadStrategy;

  const [simulations, kpis, dossierState] = await Promise.all([
    listAuditSimulationsForUser(user.id),
    getAuditKpisForUser(user.id),
    getInstitutionalDossierForUser(user.id, strategy),
  ]);

  return (
    <PageShell
      title="Modulo 10: Expediente Preventivo"
      headerMode="module"
      headerBackHref="/proteccion-legal"
      headerBackLabel="M9: Legal"
      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">Expediente Preventivo</h1>
          <p className="mt-2 text-xl text-[#4f6588] md:text-2xl">Simula auditorias y consolida evidencia institucional desde M5, M8, M9 y M7</p>
        </div>
      </section>

      <PreventiveDossierView
        initialSimulations={simulations}
        initialKpis={kpis}
        initialDossier={dossierState.dossier}
        initialFreshness={dossierState.freshness}
      />
    </PageShell>
  );
}
