import Link from "next/link";
import type { LicitationSource } from "@prisma/client";
import { hasModuleAccess } from "@/lib/auth/module-access";
import { requireOnboardedUser } from "@/lib/auth/user";
import { isLikelyPdfUrl, parseLicitationDocumentLinks, pickPrimaryLicitationPdfDocument } from "@/lib/licitations/documents";
import { getCategoryLabel, getProcedureTypeLabel } from "@/lib/licitations/labels";
import { getLicitationReviewStatusLabel, type LicitationReviewStatusView } from "@/lib/licitations/preferences";
import { listMunicipalities, searchLicitations } from "@/lib/licitations/query";
import { getAiEnhancedLicitationRecommendationsForUser } from "@/lib/licitations/ai-recommendations";
import { computeModule3Summary, getViabilityLevel } from "@/lib/licitations/module3";
import { prisma } from "@/lib/prisma";
import { LicitationCardActions } from "@/components/app/licitation-card-actions";
import { LicitationsSyncButton } from "@/components/app/licitations-sync-button";
import { PageShell } from "@/components/app/page-shell";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";

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

type ViabilityFilter = "all" | "alta" | "media" | "baja";
type SortFilter = "compat_desc" | "compat_asc" | "closing_soon" | "recent";
type StatusFilter = "all" | "open" | "closed";
type ReviewFilter = "all" | "consulted" | "interested" | "active";

function getParam(params: Record<string, string | string[] | undefined>, key: string) {
  const value = params[key];
  return Array.isArray(value) ? value[0] ?? "" : (value ?? "");
}

function parseViability(value: string): ViabilityFilter {
  if (value === "alta" || value === "media" || value === "baja") {
    return value;
  }

  return "all";
}

function parseSort(value: string): SortFilter {
  if (value === "compat_asc" || value === "closing_soon" || value === "recent") {
    return value;
  }

  return "compat_desc";
}

function parseStatus(value: string): StatusFilter {
  if (value === "open" || value === "closed") {
    return value;
  }

  return "all";
}

function parseReview(value: string): ReviewFilter {
  if (value === "consulted" || value === "interested" || value === "active") {
    return value;
  }

  return "all";
}

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

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

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

function formatAmount(amount: unknown, currency: string | null) {
  if (amount == null) {
    return "Monto no disponible";
  }

  const numeric = Number(amount);

  if (!Number.isFinite(numeric)) {
    return "Monto no disponible";
  }

  return `${currency ?? "MXN"} ${numeric.toLocaleString("es-MX", { maximumFractionDigits: 0 })}`;
}

function getSourceShortLabel(source: LicitationSource) {
  if (source === "MUNICIPAL_OPEN_PORTAL") {
    return "Portal municipal";
  }

  if (source === "MUNICIPAL_BACKUP") {
    return "Portal respaldo";
  }

  if (source === "LICITAYA") {
    return "LicitaYa API";
  }

  return "PNT";
}

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

  const now = new Date();
  const difference = value.getTime() - now.getTime();
  const dayCount = Math.max(0, Math.ceil(difference / (1000 * 60 * 60 * 24)));
  return `${dayCount} dias`;
}

function ViabilityBadge({ score }: { score: number }) {
  const level = getViabilityLevel(score);

  const label = level === "alta" ? "Alta Viabilidad" : level === "media" ? "Media Viabilidad" : "Baja Viabilidad";
  const className =
    level === "alta"
      ? "border-[#b8e3d0] bg-[#ecf9f2] text-[#1f8b63]"
      : level === "media"
        ? "border-[#f0deb0] bg-[#fff8e9] text-[#9d6d08]"
        : "border-[#f2cccc] bg-[#fff1f1] text-[#af3a3a]";

  return <span className={`inline-flex rounded-full border px-3 py-1 text-sm font-semibold ${className}`}>{label}</span>;
}

function ReviewStatusBadge({ status }: { status: LicitationReviewStatusView }) {
  const label = getLicitationReviewStatusLabel(status);
  const className =
    status === "REVIEWED"
      ? "border-[#d4dbe8] bg-[#f2f5fb] text-[#42577c]"
      : status === "INTERESTED"
        ? "border-[#b9e6cd] bg-[#eaf9f1] text-[#1f8b63]"
        : status === "DISCARDED"
          ? "border-[#f0ccd2] bg-[#fff1f4] text-[#a74150]"
          : "border-[#d4e2ff] bg-[#e8f0ff] text-[#2f58c1]";

  return <span className={`inline-flex rounded-full border px-3 py-1 text-sm font-semibold ${className}`}>{label}</span>;
}

export default async function LicitationsPage({ searchParams }: LicitationsPageProps) {
  const user = await requireOnboardedUser();
  const hasPaidModulesAccess = await hasModuleAccess(user, 3);

  if (!hasPaidModulesAccess) {
    return (
      <PageShell
        title="Modulo 3: Deteccion de Oportunidades"
        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]">
              El Modulo 3 forma parte de la ruta premium. Tu cuenta actual puede completar el Diagnostico (Modulo 1) y ver los planes en la seccion Modulos.
            </p>
            <Link href="/dashboard#modulos">
              <Button>Ver modulos y planes</Button>
            </Link>
          </CardContent>
        </Card>
      </PageShell>
    );
  }

  const params = await searchParams;
  const q = getParam(params, "q");
  const state = getParam(params, "state");
  const municipality = getParam(params, "municipality");
  const procedureType = getParam(params, "procedure_type");
  const minAmount = getParam(params, "min_amount");
  const maxAmount = getParam(params, "max_amount");
  const dateFrom = getParam(params, "date_from");
  const dateTo = getParam(params, "date_to");
  const viabilityFilter = parseViability(getParam(params, "viability"));
  const statusFilter = parseStatus(getParam(params, "status"));
  const reviewFilter = parseReview(getParam(params, "review"));
  const sortFilter = parseSort(getParam(params, "sort"));

  const [municipalities, records, recommendations] = await Promise.all([
    listMunicipalities(),
    searchLicitations({
      state,
      municipality,
      procedureType,
      q,
      minAmount,
      maxAmount,
      dateFrom,
      dateTo,
      take: 100,
    }),
    getAiEnhancedLicitationRecommendationsForUser(user.id),
  ]);

  const preferenceRecords = records.records.length
    ? await prisma.licitationUserPreference.findMany({
        where: {
          userId: user.id,
          licitationId: {
            in: records.records.map((record) => record.id),
          },
        },
        select: {
          licitationId: true,
          status: true,
        },
      })
    : [];

  const recommendationsById = new Map(recommendations.results.map((item) => [item.id, item]));
  const preferencesById = new Map(preferenceRecords.map((item) => [item.licitationId, item.status as LicitationReviewStatusView]));
  const activeProposalRecords = records.records.length
    ? await prisma.proposal.findMany({
        where: {
          userId: user.id,
          sourceLicitationId: {
            in: records.records.map((record) => record.id),
          },
          status: {
            not: "ARCHIVED",
          },
        },
        select: {
          sourceLicitationId: true,
          status: true,
          updatedAt: true,
        },
        orderBy: [{ updatedAt: "desc" }],
      })
    : [];
  const activeLicitationIds = new Set(activeProposalRecords.map((item) => item.sourceLicitationId).filter((value): value is string => Boolean(value)));

  const baseRows = records.records
    .map((record) => {
      const recommendation = recommendationsById.get(record.id);
      const deterministicScore = recommendation?.deterministicScore ?? recommendation?.score ?? 0;
      const aiFitScore = recommendation?.aiScore ?? deterministicScore;
      const blendedScore = recommendation?.blendedScore ?? deterministicScore;

      return {
        id: record.id,
        title: record.title,
        description: record.description,
        entity: record.supplierAwarded ?? "Entidad no especificada",
        municipalityName: record.municipality.municipalityName,
        stateName: record.municipality.stateName,
        amountLabel: formatAmount(record.amount, record.currency),
        daysToClose: getDaysUntilDate(record.closingDate),
        procedureLabel: getProcedureTypeLabel(record.procedureType),
        categoryLabel: getCategoryLabel(record.category),
        publishDate: record.publishDate,
        closingDate: record.closingDate,
        sourceLabel: getSourceShortLabel(record.source),
        deterministicScore,
        aiFitScore,
        compatibilityScore: blendedScore,
        blendedScore,
        reasons: recommendation?.reasons ?? [],
        aiReasons: recommendation?.aiReasons ?? [],
        aiRisks: recommendation?.aiRisks ?? [],
        nextStep: recommendation?.nextStep ?? null,
        suggestionId: recommendation?.suggestionId ?? null,
        isOpen: record.isOpen,
        reviewStatus: preferencesById.get(record.id) ?? "NEW",
        isActive: activeLicitationIds.has(record.id),
        primaryPdfUrl:
          pickPrimaryLicitationPdfDocument(parseLicitationDocumentLinks(record.documents))?.url ??
          (isLikelyPdfUrl(record.rawSourceUrl) ? record.rawSourceUrl : null),
      };
    })
    .filter((row) => {
      if (statusFilter === "open") {
        return row.isOpen;
      }

      if (statusFilter === "closed") {
        return !row.isOpen;
      }

      return true;
    })
    .filter((row) => {
      if (viabilityFilter === "all") {
        return true;
      }

      return getViabilityLevel(row.compatibilityScore) === viabilityFilter;
    });

  const rows = baseRows.filter((row) => {
      if (reviewFilter === "consulted") {
        return row.reviewStatus === "REVIEWED";
      }

      if (reviewFilter === "interested") {
        return row.reviewStatus === "INTERESTED";
      }

      if (reviewFilter === "active") {
        return row.isActive;
      }

      return true;
    });

  const sortedRows = [...rows].sort((left, right) => {
    if (sortFilter === "compat_asc") {
      return left.blendedScore - right.blendedScore;
    }

    if (sortFilter === "closing_soon") {
      const leftTime = left.closingDate?.getTime() ?? Number.MAX_SAFE_INTEGER;
      const rightTime = right.closingDate?.getTime() ?? Number.MAX_SAFE_INTEGER;
      return leftTime - rightTime;
    }

    if (sortFilter === "recent") {
      const leftTime = left.publishDate?.getTime() ?? 0;
      const rightTime = right.publishDate?.getTime() ?? 0;
      return rightTime - leftTime;
    }

    return right.blendedScore - left.blendedScore;
  });

  const uniqueStates = Array.from(new Map(municipalities.map((item) => [item.stateCode, item.stateName])).entries()).map(([code, name]) => ({
    code,
    name,
  }));

  const filteredMunicipalities = state ? municipalities.filter((item) => item.stateCode === state) : municipalities;
  const now = new Date();
  const summary = computeModule3Summary(
    sortedRows.length,
    sortedRows.map((row) => ({
      id: row.id,
      score: row.compatibilityScore,
      publishDate: row.publishDate?.toISOString() ?? null,
    })),
    now,
  );
  const newToReviewCount = sortedRows.filter((row) => row.reviewStatus === "NEW").length;
  const consultedCount = baseRows.filter((row) => row.reviewStatus === "REVIEWED").length;
  const interestedCount = baseRows.filter((row) => row.reviewStatus === "INTERESTED").length;
  const activeCount = baseRows.filter((row) => row.isActive).length;

  return (
    <PageShell
      title="Modulo 3: Deteccion de Oportunidades"
      headerMode="module"
      headerBackHref="/dashboard"
      headerBackLabel="Volver al Dashboard"
      headerShowManual
      headerPlanBadgeLabel="Plan Premium"
      showPageHeading={false}
      contentWidth="wide"
      className="space-y-6"
    >
      <section className="flex flex-wrap items-center justify-between gap-4">
        <div className="flex items-start gap-4">
          <span className="inline-flex h-14 w-14 items-center justify-center rounded-2xl bg-[#dee5f1] text-3xl text-[#264574]">✧</span>
          <div>
            <h1 className="text-4xl font-semibold text-[#132549] [font-family:var(--font-display)] md:text-5xl">Modulo 3: Deteccion de Oportunidades</h1>
            <p className="mt-2 text-xl text-[#4f6588] md:text-2xl">Encuentra licitaciones compatibles con tu perfil empresarial</p>
          </div>
        </div>
        <LicitationsSyncButton />
      </section>

      <Card className="border-[#d2dbe9] bg-[#f7f9fd]">
        <CardContent className="flex items-center justify-between py-5">
          <div>
            <p className="text-2xl font-semibold text-[#1b3158] [font-family:var(--font-display)] md:text-3xl">Como usar este modulo?</p>
            <p className="text-base text-[#566d92] md:text-lg">Guia rapida para encontrar oportunidades</p>
          </div>
          <span className="text-2xl text-[#273f67]" aria-hidden>
            ˅
          </span>
        </CardContent>
      </Card>

      <section className="grid gap-4 md:grid-cols-4">
        <Card>
          <CardContent className="py-4">
            <p className="text-4xl font-semibold text-[#12274d] md:text-5xl">{summary.opportunities}</p>
            <p className="text-lg text-[#60718f] md:text-xl">Oportunidades</p>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="py-4">
            <p className="text-4xl font-semibold text-[#12274d] md:text-5xl">{summary.highViability}</p>
            <p className="text-lg text-[#60718f] md:text-xl">Alta viabilidad</p>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="py-4">
            <p className="text-4xl font-semibold text-[#12274d] md:text-5xl">{summary.mediumViability}</p>
            <p className="text-lg text-[#60718f] md:text-xl">Media viabilidad</p>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="py-4">
            <p className="text-4xl font-semibold text-[#12274d] md:text-5xl">{summary.averageCompatibility}%</p>
            <p className="text-lg text-[#60718f] md:text-xl">Compatibilidad promedio</p>
          </CardContent>
        </Card>
      </section>

      <section className="grid gap-3 md:grid-cols-3">
        <Link href="/licitations?review=consulted" className="block">
          <Card className={reviewFilter === "consulted" ? "border-[#b8c9eb] bg-[#edf3ff]" : undefined}>
            <CardContent className="py-4">
              <p className="text-3xl font-semibold text-[#15305d]">{consultedCount}</p>
              <p className="text-sm font-semibold text-[#5f7090]">Consultadas</p>
            </CardContent>
          </Card>
        </Link>
        <Link href="/licitations?review=interested" className="block">
          <Card className={reviewFilter === "interested" ? "border-[#b9e6cd] bg-[#edf9f2]" : undefined}>
            <CardContent className="py-4">
              <p className="text-3xl font-semibold text-[#155540]">{interestedCount}</p>
              <p className="text-sm font-semibold text-[#5f7090]">Me interesa</p>
            </CardContent>
          </Card>
        </Link>
        <Link href="/licitations?review=active" className="block">
          <Card className={reviewFilter === "active" ? "border-[#f0deb0] bg-[#fff9ea]" : undefined}>
            <CardContent className="py-4">
              <p className="text-3xl font-semibold text-[#704f05]">{activeCount}</p>
              <p className="text-sm font-semibold text-[#5f7090]">Activas</p>
            </CardContent>
          </Card>
        </Link>
      </section>

      <p className="text-base text-[#4d6488] md:text-lg">
        Ultimo analisis: {formatDateShort(now)}, {now.toLocaleTimeString("es-MX", { hour: "2-digit", minute: "2-digit" })} ·
        <span className="ml-1 font-semibold text-[#1c3768]">{newToReviewCount} nuevas por revisar</span>
      </p>

      <Card>
        <CardContent className="py-4">
          <form method="get" className="space-y-4">
            <div className="grid gap-3 lg:grid-cols-[minmax(0,1fr)_220px_220px_220px_220px]">
              <label className="space-y-1 text-sm font-semibold text-[#33415c] lg:col-span-1">
                Buscar oportunidades
                <input
                  type="text"
                  name="q"
                  defaultValue={q}
                  placeholder="Buscar oportunidades..."
                  className="h-12 w-full rounded-xl border border-[#cfd8e6] px-4 text-base"
                />
              </label>

              <label className="space-y-1 text-sm font-semibold text-[#33415c]">
                Viabilidad
                <select name="viability" defaultValue={viabilityFilter} className="h-12 w-full rounded-xl border border-[#cfd8e6] px-3 text-base">
                  <option value="all">Todas</option>
                  <option value="alta">Alta</option>
                  <option value="media">Media</option>
                  <option value="baja">Baja</option>
                </select>
              </label>

              <label className="space-y-1 text-sm font-semibold text-[#33415c]">
                Estatus
                <select name="status" defaultValue={statusFilter} className="h-12 w-full rounded-xl border border-[#cfd8e6] px-3 text-base">
                  <option value="all">Todos</option>
                  <option value="open">Abiertas</option>
                  <option value="closed">Cerradas</option>
                </select>
              </label>

              <label className="space-y-1 text-sm font-semibold text-[#33415c]">
                Seguimiento M3
                <select name="review" defaultValue={reviewFilter} className="h-12 w-full rounded-xl border border-[#cfd8e6] px-3 text-base">
                  <option value="all">Todos</option>
                  <option value="consulted">Consultadas</option>
                  <option value="interested">Me interesa</option>
                  <option value="active">Activas</option>
                </select>
              </label>

              <label className="space-y-1 text-sm font-semibold text-[#33415c]">
                Ordenar por
                <select name="sort" defaultValue={sortFilter} className="h-12 w-full rounded-xl border border-[#cfd8e6] px-3 text-base">
                  <option value="compat_desc">Mayor compatibilidad</option>
                  <option value="compat_asc">Menor compatibilidad</option>
                  <option value="closing_soon">Cierre proximo</option>
                  <option value="recent">Mas recientes</option>
                </select>
              </label>
            </div>

            <div className="grid gap-3 md:grid-cols-2 lg:grid-cols-6">
              <label className="space-y-1 text-sm font-semibold text-[#33415c]">
                Procedimiento
                <select name="procedure_type" defaultValue={procedureType} className="h-12 w-full rounded-xl border border-[#cfd8e6] px-3 text-base">
                  <option value="">Todos</option>
                  <option value="LICITACION_PUBLICA">Licitacion publica</option>
                  <option value="INVITACION_RESTRINGIDA">Invitacion restringida</option>
                  <option value="ADJUDICACION_DIRECTA">Adjudicacion directa</option>
                </select>
              </label>

              <label className="space-y-1 text-sm font-semibold text-[#33415c] lg:col-span-2">
                Estado
                <select name="state" defaultValue={state} className="h-12 w-full rounded-xl border border-[#cfd8e6] px-3 text-base">
                  <option value="">Todos los estados</option>
                  {uniqueStates.map((stateOption) => (
                    <option key={stateOption.code} value={stateOption.code}>
                      {stateOption.name}
                    </option>
                  ))}
                </select>
              </label>

              <label className="space-y-1 text-sm font-semibold text-[#33415c] lg:col-span-2">
                Municipio
                <select name="municipality" defaultValue={municipality} className="h-12 w-full rounded-xl border border-[#cfd8e6] px-3 text-base">
                  <option value="">Todos</option>
                  {filteredMunicipalities.map((municipalityOption) => (
                    <option key={municipalityOption.id} value={municipalityOption.municipalityCode}>
                      {municipalityOption.municipalityName}
                    </option>
                  ))}
                </select>
              </label>

              <label className="space-y-1 text-sm font-semibold text-[#33415c]">
                Monto minimo
                <input type="number" step="0.01" name="min_amount" defaultValue={minAmount} className="h-12 w-full rounded-xl border border-[#cfd8e6] px-3 text-base" />
              </label>

              <label className="space-y-1 text-sm font-semibold text-[#33415c]">
                Monto maximo
                <input type="number" step="0.01" name="max_amount" defaultValue={maxAmount} className="h-12 w-full rounded-xl border border-[#cfd8e6] px-3 text-base" />
              </label>

              <input type="hidden" name="date_from" value={dateFrom} />
              <input type="hidden" name="date_to" value={dateTo} />

              <div className="flex items-end gap-2 lg:col-span-2">
                <Button type="submit" className="h-12 rounded-xl px-5">
                  Aplicar
                </Button>
                <Link href="/licitations" className="inline-flex">
                  <Button type="button" variant="secondary" className="h-12 rounded-xl px-5">
                    Limpiar
                  </Button>
                </Link>
              </div>
            </div>
          </form>
        </CardContent>
      </Card>

      <section className="grid gap-4 xl:grid-cols-2">
        {sortedRows.length === 0 ? (
          <Card className="xl:col-span-2">
            <CardContent className="py-14 text-center">
              <p className="text-2xl font-semibold text-[#1b3158] [font-family:var(--font-display)] md:text-3xl">No hay oportunidades con estos filtros</p>
              <p className="mt-2 text-base text-[#5f7090] md:text-lg">Ajusta los filtros o ejecuta una nueva sincronizacion.</p>
            </CardContent>
          </Card>
        ) : (
          sortedRows.map((row) => (
            <article
              key={row.id}
              className={`rounded-2xl border border-[#d7dfea] p-6 shadow-[0_1px_2px_rgba(16,24,40,0.06)] ${row.reviewStatus === "DISCARDED" ? "bg-[#fafbfe] opacity-85" : "bg-white"}`}
            >
                <div className="flex flex-wrap items-start justify-between gap-3">
              <div className="flex flex-wrap items-center gap-2">
                    <ReviewStatusBadge status={row.reviewStatus} />
                    <ViabilityBadge score={row.blendedScore} />
                    {row.isActive ? (
                      <span className="inline-flex rounded-full border border-[#f0deb0] bg-[#fff8e9] px-3 py-1 text-sm font-semibold text-[#8d6308]">Activa en M5</span>
                    ) : null}
                  </div>
                <div className="text-right">
                  <p className="text-3xl font-semibold text-[#12306a] md:text-4xl">{row.blendedScore}%</p>
                  <p className="text-base text-[#5f7290] md:text-lg">score combinado</p>
                </div>
              </div>

              <h3 className="mt-4 text-2xl font-semibold leading-tight text-[#162748] [font-family:var(--font-display)] md:text-3xl">{row.title}</h3>

              <div className="mt-4 h-4 w-full overflow-hidden rounded-full bg-[#d7e6ef]">
                <div
                  className="h-full rounded-full bg-gradient-to-r from-[#1f3f84] via-[#2576a8] to-[#2bb67f]"
                  style={{ width: `${Math.max(8, Math.min(100, row.blendedScore))}%` }}
                />
              </div>

              <div className="mt-3 grid gap-2 text-sm text-[#5d7090] md:grid-cols-3">
                <p>
                  Determinista: <span className="font-semibold text-[#17315a]">{row.deterministicScore}%</span>
                </p>
                <p>
                  AI fit: <span className="font-semibold text-[#17315a]">{row.aiFitScore}%</span>
                </p>
                <p>
                  Combinado: <span className="font-semibold text-[#17315a]">{row.blendedScore}%</span>
                </p>
              </div>

              <div className="mt-4 grid gap-2 text-base text-[#596f93] md:grid-cols-2 md:text-lg">
                <p>{row.entity}</p>
                <p>{row.municipalityName}</p>
                <p>{row.amountLabel}</p>
                <p>{row.daysToClose}</p>
              </div>

              <div className="mt-4 space-y-2 text-sm">
                <p className="font-semibold text-[#0f8a56]">Por que es compatible:</p>
                {row.aiReasons.length ? (
                  row.aiReasons.slice(0, 2).map((reason) => (
                    <span key={reason} className="mr-2 inline-flex rounded-full border border-[#b9e6cd] bg-[#eaf9f1] px-3 py-1 font-semibold text-[#1c865e]">
                      {reason}
                    </span>
                  ))
                ) : row.reasons.length ? (
                  row.reasons.slice(0, 2).map((reason) => (
                    <span key={reason} className="mr-2 inline-flex rounded-full border border-[#dbe4ef] bg-[#f4f7fb] px-3 py-1 font-semibold text-[#576b8f]">
                      {reason}
                    </span>
                  ))
                ) : (
                  <span className="inline-flex rounded-full border border-[#dbe4ef] bg-[#f4f7fb] px-3 py-1 font-semibold text-[#576b8f]">
                    Completa mas datos de perfil para mejorar recomendaciones.
                  </span>
                )}
              </div>

              {row.aiRisks.length ? (
                <div className="mt-2 space-y-1 text-sm">
                  <p className="font-semibold text-[#8d6308]">Riesgos detectados por IA:</p>
                  <div className="flex flex-wrap gap-2">
                    {row.aiRisks.slice(0, 2).map((risk) => (
                      <span key={risk} className="inline-flex rounded-full border border-[#f0deb0] bg-[#fff8e9] px-3 py-1 font-semibold text-[#8d6308]">
                        {risk}
                      </span>
                    ))}
                  </div>
                </div>
              ) : null}

              {row.nextStep ? <p className="mt-2 text-sm font-semibold text-[#264574]">Siguiente paso sugerido: {row.nextStep}</p> : null}

              <details className="mt-4 rounded-xl border border-[#dce4ef] bg-[#f9fbff] p-3">
                <summary className="cursor-pointer text-lg font-semibold text-[#1f3f84] md:text-xl">Ver resumen rapido</summary>
                <div className="mt-3 space-y-2 text-base text-[#5d7090] md:text-lg">
                  <p>Procedimiento: {row.procedureLabel}</p>
                  <p>Categoria: {row.categoryLabel}</p>
                  <p>Fuente: {row.sourceLabel}</p>
                  <p>Publicacion: {formatDate(row.publishDate)}</p>
                  <p>Cierre: {formatDate(row.closingDate)}</p>
                </div>
                <div className="mt-3">
                  <LicitationCardActions
                    licitationId={row.id}
                    initialStatus={row.reviewStatus}
                    normativeAnalysisHref={`/normative-analysis?sourceId=${encodeURIComponent(row.id)}`}
                  />
                </div>
                <div className="mt-3 flex flex-wrap gap-2">
                  <Link href={`/licitations/${encodeURIComponent(row.id)}`}>
                    <Button size="sm">Ir al detalle</Button>
                  </Link>
                  <Link href={`/normative-analysis?sourceId=${encodeURIComponent(row.id)}`}>
                    <Button size="sm" variant="secondary">
                      Analizar en M4
                    </Button>
                  </Link>
                  {row.primaryPdfUrl ? (
                    <a href={row.primaryPdfUrl} target="_blank" rel="noreferrer">
                      <Button size="sm" variant="secondary">
                        Ver PDF principal
                      </Button>
                    </a>
                  ) : null}
                  <Link href={`/gestion-licitaciones?sourceId=${encodeURIComponent(row.id)}&autocreate=1&autofill=1`}>
                    <Button size="sm" variant="secondary">
                      Crear propuesta (M5)
                    </Button>
                  </Link>
                </div>
              </details>
            </article>
          ))
        )}
      </section>

      <section className="rounded-2xl border border-[#c9dfd2] bg-[#f0faf4] px-6 py-6">
        <div className="flex flex-wrap items-center justify-between gap-3">
          <div>
            <p className="text-2xl font-semibold text-[#17315a] [font-family:var(--font-display)] md:text-3xl">Te interesa una oportunidad?</p>
            <p className="text-base text-[#5c7395] md:text-lg">Descarga las bases de licitacion y continua en Analisis Normativo (M4).</p>
          </div>
          <Link href="/normative-analysis" className="inline-flex">
            <Button size="lg" className="rounded-2xl px-7">
              Ir a Analisis Normativo (M4)
            </Button>
          </Link>
        </div>
      </section>
    </PageShell>
  );
}
