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 { listUserProposals } from "@/lib/proposals/server";
import { PageShell } from "@/components/app/page-shell";
import { ProposalsManagementView } from "@/components/app/proposals-management-view";
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 GestionLicitacionesPage({ searchParams }: PageProps) {
  const user = await requireOnboardedUser();
  const hasPaidModulesAccess = await hasModuleAccess(user, 5);

  if (!hasPaidModulesAccess) {
    return (
      <PageShell
        title="Modulo 5: Gestion de Licitaciones"
        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 5 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="/normative-analysis">
                <Button variant="secondary">Ir a Modulo 4</Button>
              </Link>
            </div>
          </CardContent>
        </Card>
      </PageShell>
    );
  }

  const resolvedSearchParams = await searchParams;
  const sourceLicitationId = getParam(resolvedSearchParams, "sourceId") || null;
  const shouldAutoCreate = getParam(resolvedSearchParams, "autocreate") === "1";
  const shouldAutoFill = getParam(resolvedSearchParams, "autofill") === "1";

  if (sourceLicitationId && shouldAutoCreate) {
    const existing = await prisma.proposal.findFirst({
      where: {
        userId: user.id,
        sourceLicitationId,
      },
      orderBy: [{ updatedAt: "desc" }],
      select: { id: true },
    });

    let targetId = existing?.id ?? null;

    if (!targetId) {
      const source = await prisma.licitation.findUnique({
        where: { id: sourceLicitationId },
        select: {
          id: true,
          title: true,
          description: true,
          supplierAwarded: true,
        },
      });

      if (source) {
        const created = await prisma.proposal.create({
          data: {
            userId: user.id,
            sourceLicitationId: source.id,
            title: source.title,
            issuingEntity: source.supplierAwarded?.trim() || "Entidad no especificada",
            summary: source.description ?? "",
          },
          select: { id: true },
        });

        targetId = created.id;
      }
    }

    if (targetId) {
      redirect(`/gestion-licitaciones/${encodeURIComponent(targetId)}${shouldAutoFill ? "?autofill=1" : ""}`);
    }
  }

  const proposals = await listUserProposals(user.id, "");
  const latestProposal = proposals[0] ?? null;
  const candadosHref =
    latestProposal
      ? `/candados?proposalId=${encodeURIComponent(latestProposal.id)}${
          latestProposal.sourceLicitationId ? `&sourceId=${encodeURIComponent(latestProposal.sourceLicitationId)}` : ""
        }`
      : sourceLicitationId
        ? `/candados?sourceId=${encodeURIComponent(sourceLicitationId)}`
        : "/candados";

  return (
    <PageShell
      title="Modulo 5: Gestion de Licitaciones"
      headerMode="module"
      headerBackHref="/normative-analysis"
      headerBackLabel="M4: Analisis"
      headerNextHref={candadosHref}
      headerNextLabel="M6: Candados"
      headerPlanBadgeLabel="Plan Premium"
      showPageHeading={false}
      contentWidth="wide"
      className="space-y-6"
    >
      <section className="flex flex-wrap items-center justify-between gap-4">
        <div>
          <h1 className="text-4xl font-semibold text-[#132549] [font-family:var(--font-display)] md:text-5xl">Gestion de Licitaciones</h1>
          <p className="mt-2 text-xl text-[#4f6588] md:text-2xl">Prepara tus propuestas de licitacion paso a paso</p>
        </div>
      </section>

      <ProposalsManagementView initialProposals={proposals} initialSourceLicitationId={sourceLicitationId} />
    </PageShell>
  );
}
