import Link from "next/link";
import { hasModuleAccess } from "@/lib/auth/module-access";
import { requireOnboardedUser } from "@/lib/auth/user";
import { listLegalTemplates } from "@/lib/legal/ai-documents";
import { getLegalKpisForUser, listLegalCasesForUser, listLegalDirectory } from "@/lib/legal/server";
import { prisma } from "@/lib/prisma";
import { LegalProtectionView } from "@/components/app/legal-protection-view";
import { PageShell } from "@/components/app/page-shell";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";

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

  if (!hasPaidModulesAccess) {
    return (
      <PageShell
        title="Modulo 9: Proteccion Legal"
        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 9 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="/gestion-contratos">
                <Button variant="secondary">Ir a Modulo 8</Button>
              </Link>
            </div>
          </CardContent>
        </Card>
      </PageShell>
    );
  }

  const resolvedSearchParams = await searchParams;
  const contractId = getParam(resolvedSearchParams, "contractId") || null;

  const [cases, kpis, directory, contracts] = await Promise.all([
    listLegalCasesForUser(user.id),
    getLegalKpisForUser(user.id),
    listLegalDirectory({}),
    prisma.contractRecord.findMany({
      where: { userId: user.id },
      orderBy: [{ updatedAt: "desc" }],
      select: {
        id: true,
        title: true,
        contractNumber: true,
        counterpartyEntity: true,
        status: true,
      },
      take: 200,
    }),
  ]);
  const templates = listLegalTemplates();

  return (
    <PageShell
      title="Modulo 9: Proteccion Legal"
      headerMode="module"
      headerBackHref="/gestion-contratos"
      headerBackLabel="M8: Contratos"
      headerNextHref="/expediente-preventivo"
      headerNextLabel="M10: Auditorias"
      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">Proteccion Legal</h1>
          <p className="mt-2 text-xl text-[#4f6588] md:text-2xl">Diagnostico guiado, gestion de casos, escalada y generacion de escritos con trazabilidad</p>
        </div>
      </section>

      <LegalProtectionView
        initialCases={cases}
        initialKpis={kpis}
        initialDirectory={directory}
        initialTemplates={templates}
        availableContracts={contracts}
        prefilledContractId={contractId}
      />
    </PageShell>
  );
}
