import Link from "next/link";
import { notFound } from "next/navigation";
import { Prisma } from "@prisma/client";
import { hasModuleAccess } from "@/lib/auth/module-access";
import { requireOnboardedUser } from "@/lib/auth/user";
import { toNormativeHistoryView } from "@/lib/normative-analysis/history";
import { prisma } from "@/lib/prisma";
import { buildRequirementSeeds, buildTechnicalSectionSeeds, type WorkflowMilestoneSeed } from "@/lib/proposals/workflow";
import { PageShell } from "@/components/app/page-shell";
import { ProposalWorkflowView } from "@/components/app/proposal-workflow-view";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";

type PageProps = {
  params: Promise<{ id: string }>;
  searchParams: Promise<Record<string, string | string[] | undefined>>;
};

type SourceDocumentLink = {
  name: string;
  url: string;
  type: string | null;
};

function toSourceDocumentLinks(value: unknown): SourceDocumentLink[] {
  if (!Array.isArray(value)) {
    return [];
  }

  return value
    .map((item) => {
      if (!item || typeof item !== "object") {
        return null;
      }

      const record = item as Record<string, unknown>;
      const name = typeof record.name === "string" && record.name.trim() ? record.name.trim() : "Documento";
      const url = typeof record.url === "string" && record.url.trim() ? record.url.trim() : "";
      const type = typeof record.type === "string" && record.type.trim() ? record.type.trim() : null;

      if (!url) {
        return null;
      }

      return { name, url, type };
    })
    .filter((item): item is SourceDocumentLink => Boolean(item));
}

function parseDateCandidate(value: unknown) {
  if (typeof value !== "string") {
    return null;
  }

  const parsed = new Date(value);
  if (Number.isNaN(parsed.getTime())) {
    return null;
  }

  return parsed;
}

function toMilestoneSeeds(args: {
  openingDate: Date | null;
  closingDate: Date | null;
  eventDates: Prisma.JsonValue | null;
}): WorkflowMilestoneSeed[] {
  const milestones: WorkflowMilestoneSeed[] = [];

  if (args.openingDate) {
    milestones.push({
      id: "opening-date",
      title: "Apertura del proceso",
      dateIso: args.openingDate.toISOString(),
      location: "",
      note: "",
      source: "licitation",
    });
  }

  if (args.closingDate) {
    milestones.push({
      id: "closing-date",
      title: "Presentacion de propuestas",
      dateIso: args.closingDate.toISOString(),
      location: "",
      note: "",
      source: "licitation",
    });
  }

  if (args.eventDates && typeof args.eventDates === "object" && !Array.isArray(args.eventDates)) {
    const entries = Object.entries(args.eventDates as Record<string, unknown>);
    for (let index = 0; index < entries.length; index += 1) {
      const [key, value] = entries[index];
      const parsed = parseDateCandidate(value);
      milestones.push({
        id: `event-date-${index + 1}`,
        title: key || `Evento ${index + 1}`,
        dateIso: parsed ? parsed.toISOString() : null,
        location: "",
        note: "",
        source: "licitation",
      });
    }
  }

  const dedupe = new Set<string>();
  return milestones.filter((item) => {
    const signature = `${item.title.toLowerCase()}|${item.dateIso ?? ""}`;
    if (dedupe.has(signature)) {
      return false;
    }
    dedupe.add(signature);
    return true;
  });
}

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 GestionLicitacionDetailPage({ params, 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 { id } = await params;
  const resolvedSearchParams = await searchParams;
  const autoExtractOnLoad = getParam(resolvedSearchParams, "autofill") === "1";

  const proposal = await prisma.proposal.findFirst({
    where: {
      id,
      userId: user.id,
    },
    select: {
      id: true,
      title: true,
      issuingEntity: true,
      summary: true,
      status: true,
      sourceLicitationId: true,
      updatedAt: true,
      documents: {
        orderBy: [{ createdAt: "desc" }],
        select: {
          id: true,
          fileName: true,
          mimeType: true,
          sizeBytes: true,
          createdAt: true,
        },
      },
    },
  });

  if (!proposal) {
    notFound();
  }

  const linkedSource = proposal.sourceLicitationId
    ? await prisma.licitation.findUnique({
        where: { id: proposal.sourceLicitationId },
        include: {
          municipality: {
            select: {
              stateName: true,
              municipalityName: true,
            },
          },
        },
      })
    : null;

  const historyEntry = proposal.sourceLicitationId
    ? await prisma.normativeAnalysisHistory.findFirst({
        where: {
          userId: user.id,
          deletedAt: null,
          sourceLicitationId: proposal.sourceLicitationId,
        },
        orderBy: [{ analyzedAt: "desc" }],
        select: {
          id: true,
          sourceLicitationId: true,
          fileName: true,
          documentType: true,
          issuingEntity: true,
          methodUsed: true,
          numPages: true,
          warnings: true,
          extractedChars: true,
          analyzedAt: true,
          viabilityScore: true,
          riskLevel: true,
          confidence: true,
          result: true,
        },
      })
    : null;

  const historyView = historyEntry ? toNormativeHistoryView(historyEntry) : null;
  const requirementSeeds = historyView ? buildRequirementSeeds(historyView.result) : [];
  const technicalSeeds = historyView ? buildTechnicalSectionSeeds(historyView.result) : [];
  const milestoneSeeds = linkedSource
    ? toMilestoneSeeds({
        openingDate: linkedSource.openingDate,
        closingDate: linkedSource.closingDate,
        eventDates: linkedSource.eventDates,
      })
    : [];
  const sourceDocumentLinks = linkedSource ? toSourceDocumentLinks(linkedSource.documents) : [];
  const candadosHref =
    `/candados?proposalId=${encodeURIComponent(proposal.id)}` +
    (proposal.sourceLicitationId ? `&sourceId=${encodeURIComponent(proposal.sourceLicitationId)}` : "");

  return (
    <PageShell
      title="Modulo 5: Gestion de Licitaciones"
      headerMode="module"
      headerBackHref="/gestion-licitaciones"
      headerBackLabel="M5: Lista"
      headerNextHref={candadosHref}
      headerNextLabel="M6: Candados"
      headerPlanBadgeLabel="Plan Premium"
      showPageHeading={false}
      contentWidth="wide"
      className="space-y-6"
    >
      <ProposalWorkflowView
        proposal={{
          id: proposal.id,
          title: proposal.title,
          issuingEntity: proposal.issuingEntity,
          summary: proposal.summary,
          status: proposal.status,
          sourceLicitationId: proposal.sourceLicitationId,
          updatedAt: proposal.updatedAt.toISOString(),
          documents: proposal.documents.map((document) => ({
            id: document.id,
            fileName: document.fileName,
            mimeType: document.mimeType,
            sizeBytes: document.sizeBytes,
            createdAt: document.createdAt.toISOString(),
          })),
        }}
        linkedSource={
          linkedSource
            ? {
                id: linkedSource.id,
                title: linkedSource.title,
                description: linkedSource.description ?? "",
                issuingEntity: linkedSource.supplierAwarded ?? null,
                procedureType: linkedSource.procedureType,
                stateName: linkedSource.municipality.stateName,
                municipalityName: linkedSource.municipality.municipalityName,
                sourceUrl: linkedSource.rawSourceUrl ?? null,
                documentLinks: sourceDocumentLinks,
                milestones: milestoneSeeds,
              }
            : null
        }
        normativeContext={
          historyView
            ? {
                id: historyView.id,
                analyzedAt: historyView.analyzedAt,
                executiveSummary: historyView.result.executiveSummary,
                confidence: historyView.confidence,
                requirementSeeds,
                technicalSeeds,
              }
            : null
        }
        autoExtractOnLoad={autoExtractOnLoad}
      />
    </PageShell>
  );
}
