import Link from "next/link";
import { redirect } from "next/navigation";
import { hasModuleAccess } from "@/lib/auth/module-access";
import { requireOnboardedUser } from "@/lib/auth/user";
import { prisma } from "@/lib/prisma";
import { getContractsKpisForUser, listContractsForUser } from "@/lib/contracts/server";
import {
  ensureProposalPdfLinkedToContract,
  getLatestProposalPdfSourceForUser,
  isPdfProposalDocument,
} from "@/lib/contracts/proposal-continuity";
import { ContractsManagementView } from "@/components/app/contracts-management-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 ?? "");
}

function logContinuityHandoff(event: string, data: Record<string, unknown>) {
  console.info(
    "[continuity_handoff]",
    JSON.stringify({
      event,
      at: new Date().toISOString(),
      ...data,
    }),
  );
}

export default async function GestionContratosPage({ searchParams }: PageProps) {
  const user = await requireOnboardedUser();
  const hasPaidModulesAccess = await hasModuleAccess(user, 8);

  if (!hasPaidModulesAccess) {
    return (
      <PageShell
        title="Modulo 8: Gestion Estrategica de Contratos"
        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 8 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="/compliance-alerts">
                <Button variant="secondary">Ir a Modulo 7</Button>
              </Link>
            </div>
          </CardContent>
        </Card>
      </PageShell>
    );
  }

  const resolvedSearchParams = await searchParams;
  const proposalId = getParam(resolvedSearchParams, "proposalId") || null;
  const shouldAutoCreate = getParam(resolvedSearchParams, "autocreate") === "1";

  if (proposalId || shouldAutoCreate) {
    logContinuityHandoff("m5_to_m8_autocreate_requested", {
      userId: user.id,
      proposalId,
      shouldAutoCreate,
    });
  }

  if (proposalId && shouldAutoCreate) {
    const ownedProposal = await prisma.proposal.findFirst({
      where: {
        id: proposalId,
        userId: user.id,
      },
      select: {
        id: true,
        title: true,
        issuingEntity: true,
        summary: true,
      },
    });

    if (ownedProposal) {
      logContinuityHandoff("m5_to_m8_autocreate_proposal_resolved", {
        userId: user.id,
        proposalId: ownedProposal.id,
      });

      const existing = await prisma.contractRecord.findFirst({
        where: {
          userId: user.id,
          sourceProposalId: ownedProposal.id,
        },
        select: {
          id: true,
        },
      });

      let targetContractId = existing?.id ?? null;
      if (!targetContractId) {
        const created = await prisma.contractRecord.create({
          data: {
            userId: user.id,
            sourceProposalId: ownedProposal.id,
            title: ownedProposal.title,
            counterpartyEntity: ownedProposal.issuingEntity,
            contractType: "Desde propuesta adjudicada",
            description: ownedProposal.summary,
            status: "ACTIVE",
            currency: "MXN",
          },
          select: {
            id: true,
          },
        });
        targetContractId = created.id;
      }
      logContinuityHandoff("m5_to_m8_autocreate_contract_resolved", {
        userId: user.id,
        proposalId: ownedProposal.id,
        contractId: targetContractId,
        mode: existing ? "reuse" : "create",
      });

      if (targetContractId) {
        try {
          const proposalPdfLookup = await getLatestProposalPdfSourceForUser(user.id, ownedProposal.id);
          logContinuityHandoff("m5_to_m8_autocreate_proposal_pdf_lookup", {
            userId: user.id,
            proposalId: ownedProposal.id,
            contractId: targetContractId,
            lookupStatus: proposalPdfLookup.status,
          });

          if (proposalPdfLookup.status === "ok") {
            const linked = await ensureProposalPdfLinkedToContract({
              userId: user.id,
              contractId: targetContractId,
              source: proposalPdfLookup.source,
            });
            logContinuityHandoff("m5_to_m8_autocreate_pdf_linked", {
              userId: user.id,
              proposalId: ownedProposal.id,
              contractId: targetContractId,
              created: linked.created,
              documentId: linked.documentId,
            });
          }
        } catch {
          logContinuityHandoff("m5_to_m8_autocreate_pdf_link_failed", {
            userId: user.id,
            proposalId: ownedProposal.id,
            contractId: targetContractId,
          });
          // Preserve autocreate flow even if continuity copy fails unexpectedly.
        }
      }

      redirect("/gestion-contratos");
    }
  }

  const [contracts, kpis, proposals] = await Promise.all([
    listContractsForUser(user.id),
    getContractsKpisForUser(user.id),
    prisma.proposal.findMany({
      where: {
        userId: user.id,
      },
      orderBy: [{ updatedAt: "desc" }],
      select: {
        id: true,
        title: true,
        documents: {
          orderBy: [{ createdAt: "desc" }],
          select: {
            id: true,
            fileName: true,
            mimeType: true,
            createdAt: true,
          },
        },
      },
      take: 200,
    }),
  ]);
  const proposalPdfOptions = proposals
    .map((proposal) => {
      const latestPdf = proposal.documents.find((document) => isPdfProposalDocument(document)) ?? null;
      if (!latestPdf) {
        return null;
      }

      return {
        proposalId: proposal.id,
        proposalTitle: proposal.title,
        documentId: latestPdf.id,
        fileName: latestPdf.fileName,
        createdAt: latestPdf.createdAt.toISOString(),
      };
    })
    .filter((item): item is { proposalId: string; proposalTitle: string; documentId: string; fileName: string; createdAt: string } => Boolean(item));

  return (
    <PageShell
      title="Modulo 8: Gestion Estrategica de Contratos"
      headerMode="module"
      headerBackHref="/compliance-alerts"
      headerBackLabel="M7: Alertas"
      headerNextHref="/proteccion-legal"
      headerNextLabel="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">Gestion Estrategica de Contratos</h1>
          <p className="mt-2 text-xl text-[#4f6588] md:text-2xl">Registra contratos, entregables, pagos y evidencia documental con trazabilidad completa</p>
        </div>
      </section>

      <ContractsManagementView initialContracts={contracts} initialKpis={kpis} proposalPdfOptions={proposalPdfOptions} />
    </PageShell>
  );
}
