import Link from "next/link";
import { notFound } from "next/navigation";
import { isAdminIdentity } from "@/lib/auth/admin";
import { requireOnboardedUser } from "@/lib/auth/user";
import { getCategoryLabel, getProcedureTypeLabel, getSourceLabel } from "@/lib/licitations/labels";
import { prisma } from "@/lib/prisma";
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) {
  if (!Array.isArray(value)) {
    return [] as Array<{ name: string; url: string; type?: string }>;
  }

  return value
    .filter((item) => item && typeof item === "object")
    .map((item) => {
      const entry = item as Record<string, unknown>;

      return {
        name: typeof entry.name === "string" ? entry.name : "Documento",
        url: typeof entry.url === "string" ? entry.url : "",
        type: typeof entry.type === "string" ? entry.type : undefined,
      };
    })
    .filter((item) => item.url.length > 0);
}

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 = isAdminIdentity(user.email, user.role);

  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 timeline = toEventDates(licitation.eventDates);

  return (
    <PageShell
      title="Detalle de licitacion"
      description={`${licitation.municipality.municipalityName}, ${licitation.municipality.stateName}`}
      action={
        <Link href="/licitations">
          <Button variant="secondary">Volver a resultados</Button>
        </Link>
      }
    >
      <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>

          <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">
          {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>
  );
}
