import Link from "next/link";
import { notFound } from "next/navigation";
import { hasModuleAccess } from "@/lib/auth/module-access";
import { requireOnboardedUser } from "@/lib/auth/user";
import { isLikelyPdfUrl, parseLicitationDocumentLinks, pickPrimaryLicitationPdfDocument } from "@/lib/licitations/documents";
import { getCategoryLabel, getProcedureTypeLabel, getSourceLabel } from "@/lib/licitations/labels";
import { type LicitationReviewStatusView } from "@/lib/licitations/preferences";
import { prisma } from "@/lib/prisma";
import { LicitationCardActions } from "@/components/app/licitation-card-actions";
import { PageShell } from "@/components/app/page-shell";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader } from "@/components/ui/card";

type LicitationDetailPageProps = {
  params: Promise<{ id: string }>;
};

function formatDate(value: Date | null) {
  if (!value) {
    return "Sin fecha";
  }

  return value.toLocaleDateString("es-MX", {
    year: "numeric",
    month: "long",
    day: "2-digit",
  });
}

function toDocumentArray(value: unknown) {
  return parseLicitationDocumentLinks(value).map((item) => ({
    ...item,
    type: item.type ?? undefined,
  }));
}

function toEventDates(value: unknown) {
  if (!value || typeof value !== "object") {
    return [] as Array<{ key: string; date: Date | null }>;
  }

  return Object.entries(value as Record<string, unknown>).map(([key, raw]) => {
    const parsed = typeof raw === "string" ? new Date(raw) : null;

    return {
      key,
      date: parsed && !Number.isNaN(parsed.getTime()) ? parsed : null,
    };
  });
}

export default async function LicitationDetailPage({ params }: LicitationDetailPageProps) {
  const user = await requireOnboardedUser();
  const hasPaidModulesAccess = await hasModuleAccess(user, 3);

  if (!hasPaidModulesAccess) {
    return (
      <PageShell title="Detalle de licitacion" description="Acceso restringido al modulo premium.">
        <Card>
          <CardHeader>
            <h2 className="text-lg font-semibold text-[#1f2a40]">Acceso restringido</h2>
          </CardHeader>
          <CardContent className="space-y-3">
            <p className="text-sm text-[#64718a]">Necesitas un plan con acceso al Modulo 3 para ver los detalles de oportunidades.</p>
            <Link href="/dashboard#modulos">
              <Button>Ver modulos y planes</Button>
            </Link>
          </CardContent>
        </Card>
      </PageShell>
    );
  }

  const { id } = await params;

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

  if (!licitation) {
    notFound();
  }

  const documents = toDocumentArray(licitation.documents);
  const primaryPdfDocument =
    pickPrimaryLicitationPdfDocument(parseLicitationDocumentLinks(licitation.documents)) ??
    (isLikelyPdfUrl(licitation.rawSourceUrl)
      ? {
          name: "Documento principal",
          url: licitation.rawSourceUrl as string,
          type: "PDF",
        }
      : null);
  const timeline = toEventDates(licitation.eventDates);
  const preference = await prisma.licitationUserPreference.findUnique({
    where: {
      userId_licitationId: {
        userId: user.id,
        licitationId: licitation.id,
      },
    },
    select: {
      status: true,
    },
  });
  const reviewStatus = (preference?.status as LicitationReviewStatusView | undefined) ?? "NEW";

  return (
    <PageShell
      title="Detalle de licitacion"
      description={`${licitation.municipality.municipalityName}, ${licitation.municipality.stateName}`}
      headerMode="module"
      headerBackHref="/licitations"
      headerBackLabel="Volver a Oportunidades"
      headerShowManual
      headerPlanBadgeLabel="Plan Premium"
      contentWidth="wide"
      action={
        <div className="flex gap-2">
          <Link href={`/normative-analysis?sourceId=${encodeURIComponent(licitation.id)}`}>
            <Button>Analizar en Modulo 4</Button>
          </Link>
          <Link href={`/gestion-licitaciones?sourceId=${encodeURIComponent(licitation.id)}&autocreate=1&autofill=1`}>
            <Button variant="secondary">Crear propuesta (M5)</Button>
          </Link>
          {primaryPdfDocument ? (
            <a href={primaryPdfDocument.url} target="_blank" rel="noreferrer">
              <Button variant="secondary">Ver PDF principal</Button>
            </a>
          ) : null}
          <Link href="/licitations">
            <Button variant="secondary">Volver a resultados</Button>
          </Link>
        </div>
      }
    >
      <Card>
        <CardHeader>
          <h2 className="text-2xl font-semibold text-[#1f2a40]">{licitation.title}</h2>
          <p className="text-sm text-[#5f6f8c]">{licitation.description ?? "Sin descripcion"}</p>
        </CardHeader>
        <CardContent className="space-y-3">
          <div className="flex flex-wrap gap-2 text-xs text-[#5f6f8c]">
            <span className={`rounded-full border px-2 py-1 ${licitation.isOpen ? "border-[#acd8c7] bg-[#e8f7ef] text-[#1c8f67]" : "border-[#d8e1ef]"}`}>
              {licitation.isOpen ? "Abierta" : "Cerrada"}
            </span>
            <span className="rounded-full border border-[#d8e1ef] px-2 py-1">{getProcedureTypeLabel(licitation.procedureType)}</span>
            <span className="rounded-full border border-[#d8e1ef] px-2 py-1">{getCategoryLabel(licitation.category)}</span>
            <span className="rounded-full border border-[#d8e1ef] px-2 py-1">Fuente: {getSourceLabel(licitation.source)}</span>
            <span className="rounded-full border border-[#d8e1ef] px-2 py-1">Publicado: {formatDate(licitation.publishDate)}</span>
            <span className="rounded-full border border-[#d8e1ef] px-2 py-1">Apertura: {formatDate(licitation.openingDate)}</span>
            <span className="rounded-full border border-[#d8e1ef] px-2 py-1">Cierre: {formatDate(licitation.closingDate)}</span>
          </div>

          <LicitationCardActions
            licitationId={licitation.id}
            initialStatus={reviewStatus}
            normativeAnalysisHref={`/normative-analysis?sourceId=${encodeURIComponent(licitation.id)}`}
          />

          <div className="grid gap-3 md:grid-cols-2">
            <div className="rounded-xl border border-[#d8e1ef] p-3">
              <p className="text-xs font-semibold uppercase text-[#60718f]">Monto</p>
              <p className="text-sm text-[#1f2a40]">
                {licitation.amount == null
                  ? "Monto no disponible"
                  : `${licitation.currency ?? "MXN"} ${Number(licitation.amount).toLocaleString("es-MX", { maximumFractionDigits: 2 })}`}
              </p>
            </div>

            <div className="rounded-xl border border-[#d8e1ef] p-3">
              <p className="text-xs font-semibold uppercase text-[#60718f]">Codigo de licitacion</p>
              <p className="text-sm text-[#1f2a40]">{licitation.tenderCode ?? "No disponible"}</p>
            </div>
          </div>

          <div className="rounded-xl border border-[#d8e1ef] p-3">
            <p className="text-xs font-semibold uppercase text-[#60718f]">Proveedor adjudicado</p>
            <p className="text-sm text-[#1f2a40]">{licitation.supplierAwarded ?? "No disponible"}</p>
          </div>

          {licitation.status ? (
            <div className="rounded-xl border border-[#d8e1ef] p-3">
              <p className="text-xs font-semibold uppercase text-[#60718f]">Estatus</p>
              <p className="text-sm text-[#1f2a40]">{licitation.status}</p>
            </div>
          ) : null}

          {licitation.rawSourceUrl ? (
            <a href={licitation.rawSourceUrl} target="_blank" rel="noreferrer" className="inline-flex text-sm font-semibold text-[#1f3f84]">
              Abrir fuente original
            </a>
          ) : null}
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <h3 className="text-lg font-semibold text-[#1f2a40]">Documentos</h3>
        </CardHeader>
        <CardContent className="space-y-2">
          {primaryPdfDocument ? (
            <a
              href={primaryPdfDocument.url}
              target="_blank"
              rel="noreferrer"
              className="block rounded-xl border border-[#c6d8f4] bg-[#ebf3ff] p-3 text-sm font-semibold text-[#1f3f84]"
            >
              PDF principal: {primaryPdfDocument.name}
            </a>
          ) : null}
          {documents.length === 0 ? (
            <p className="text-sm text-[#64718a]">No hay documentos asociados.</p>
          ) : (
            documents.map((document, index) => (
              <a key={`${document.url}-${index}`} href={document.url} target="_blank" rel="noreferrer" className="block rounded-xl border border-[#d8e1ef] p-3 text-sm text-[#1f3f84]">
                {document.name} {document.type ? `(${document.type})` : ""}
              </a>
            ))
          )}
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <h3 className="text-lg font-semibold text-[#1f2a40]">Linea de tiempo</h3>
        </CardHeader>
        <CardContent className="space-y-2">
          {timeline.length === 0 ? (
            <p className="text-sm text-[#64718a]">No hay fechas de eventos registradas.</p>
          ) : (
            timeline.map((event) => (
              <div key={event.key} className="rounded-xl border border-[#d8e1ef] p-3 text-sm text-[#1f2a40]">
                <p className="font-semibold text-[#2b3d5d]">{event.key}</p>
                <p>{formatDate(event.date)}</p>
              </div>
            ))
          )}
        </CardContent>
      </Card>
    </PageShell>
  );
}
