import Link from "next/link";
import { LicitationProcedureType } from "@prisma/client";
import { isAdminIdentity } from "@/lib/auth/admin";
import { requireOnboardedUser } from "@/lib/auth/user";
import { getCategoryLabel, getProcedureTypeLabel, getSourceLabel } from "@/lib/licitations/labels";
import { listMunicipalities, searchLicitations } from "@/lib/licitations/query";
import { getLicitationRecommendationsForUser } from "@/lib/licitations/recommendations";
import { LicitationsSyncButton } from "@/components/app/licitations-sync-button";
import { PageShell } from "@/components/app/page-shell";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader } from "@/components/ui/card";

type LicitationsPageProps = {
  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;
}

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

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

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: 2 })}`;
}

export default async function LicitationsPage({ searchParams }: LicitationsPageProps) {
  const user = await requireOnboardedUser();
  const hasPaidModulesAccess = isAdminIdentity(user.email, user.role);

  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>
          <CardHeader>
            <h2 className="text-lg font-semibold text-[#1f2a40]">Acceso restringido</h2>
          </CardHeader>
          <CardContent className="space-y-3">
            <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 [municipalities, records, recommendations] = await Promise.all([
    listMunicipalities(),
    searchLicitations({
      state,
      municipality,
      procedureType,
      q,
      minAmount,
      maxAmount,
      dateFrom,
      dateTo,
      take: 100,
    }),
    getLicitationRecommendationsForUser(user.id),
  ]);

  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;

  return (
    <PageShell
      title="Modulo 3: Deteccion de Oportunidades"
      description="Encuentra licitaciones compatibles con tu perfil empresarial"
      action={<LicitationsSyncButton />}
      className="space-y-6"
    >
      <Card>
        <CardContent className="py-4">
          <form method="get" className="grid gap-3 md:grid-cols-3">
            <label className="space-y-1 text-sm font-semibold text-[#33415c] md:col-span-2">
              Buscar oportunidades
              <input
                type="text"
                name="q"
                defaultValue={q}
                placeholder="Palabra clave, proveedor, concepto..."
                className="h-10 w-full rounded-lg border border-[#cfd8e6] px-3 text-sm"
              />
            </label>

            <label className="space-y-1 text-sm font-semibold text-[#33415c]">
              Tipo de procedimiento
              <select name="procedure_type" defaultValue={procedureType} className="h-10 w-full rounded-lg border border-[#cfd8e6] px-3 text-sm">
                <option value="">Todos</option>
                <option value={LicitationProcedureType.LICITACION_PUBLICA}>Licitacion publica</option>
                <option value={LicitationProcedureType.INVITACION_RESTRINGIDA}>Invitacion restringida</option>
                <option value={LicitationProcedureType.ADJUDICACION_DIRECTA}>Adjudicacion directa</option>
              </select>
            </label>

            <label className="space-y-1 text-sm font-semibold text-[#33415c]">
              Estado
              <select name="state" defaultValue={state} className="h-10 w-full rounded-lg border border-[#cfd8e6] px-3 text-sm">
                <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]">
              Municipio
              <select name="municipality" defaultValue={municipality} className="h-10 w-full rounded-lg border border-[#cfd8e6] px-3 text-sm">
                <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-10 w-full rounded-lg border border-[#cfd8e6] px-3 text-sm" />
            </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-10 w-full rounded-lg border border-[#cfd8e6] px-3 text-sm" />
            </label>

            <label className="space-y-1 text-sm font-semibold text-[#33415c]">
              Fecha desde
              <input type="date" name="date_from" defaultValue={dateFrom} className="h-10 w-full rounded-lg border border-[#cfd8e6] px-3 text-sm" />
            </label>

            <label className="space-y-1 text-sm font-semibold text-[#33415c]">
              Fecha hasta
              <input type="date" name="date_to" defaultValue={dateTo} className="h-10 w-full rounded-lg border border-[#cfd8e6] px-3 text-sm" />
            </label>

            <div className="md:col-span-3 flex gap-2">
              <Button type="submit">Aplicar filtros</Button>
              <Link href="/licitations">
                <Button type="button" variant="secondary">
                  Limpiar
                </Button>
              </Link>
            </div>
          </form>
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <h2 className="text-lg font-semibold text-[#1f2a40]">Recomendaciones para tu empresa</h2>
        </CardHeader>
        <CardContent className="space-y-3">
          {recommendations.results.slice(0, 5).length ? (
            recommendations.results.slice(0, 5).map((item) => (
              <div key={item.id} className="rounded-xl border border-[#d8e1ef] bg-white p-3">
                <div className="flex flex-wrap items-center justify-between gap-2">
                  <p className="text-sm font-semibold text-[#1f2f4f]">{item.title}</p>
                  <span className="rounded-full bg-[#e8eefc] px-2 py-1 text-xs font-semibold text-[#1a3f8d]">Score {item.score}</span>
                </div>
                <p className="mt-1 text-sm text-[#5c6f8e]">{item.municipalityName}, {item.stateName}</p>
                <p className="mt-1 text-xs text-[#5c6f8e]">{item.reasons.join(" ")}</p>
                <Link href={`/licitations/${item.id}`} className="mt-2 inline-flex text-sm font-semibold text-[#1f3f84]">
                  Ver detalle
                </Link>
              </div>
            ))
          ) : (
            <p className="text-sm text-[#64718a]">Aun no hay recomendaciones por perfil. Completa tu perfil y ejecuta sincronizacion.</p>
          )}
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <h2 className="text-lg font-semibold text-[#1f2a40]">Resultados ({records.total})</h2>
          <p className="text-sm text-[#60718f]">Mostrando oportunidades abiertas por defecto.</p>
        </CardHeader>
        <CardContent className="space-y-3">
          {records.records.length === 0 ? (
            <p className="text-sm text-[#64718a]">No se encontraron oportunidades con los filtros seleccionados.</p>
          ) : (
            records.records.map((record) => (
              <article key={record.id} className="rounded-xl border border-[#d8e1ef] bg-white p-4">
                <div className="flex flex-wrap items-start justify-between gap-2">
                  <div>
                    <p className="text-xs font-semibold uppercase text-[#60718f]">{record.municipality.stateName} / {record.municipality.municipalityName}</p>
                    <h3 className="text-lg font-semibold text-[#1f2a40]">{record.title}</h3>
                    <p className="text-sm text-[#60718f]">{record.description ?? "Sin descripcion"}</p>
                  </div>
                  <span className="rounded-full bg-[#eef3ff] px-2 py-1 text-xs font-semibold text-[#1f3f84]">{getProcedureTypeLabel(record.procedureType)}</span>
                </div>

                <div className="mt-3 flex flex-wrap items-center gap-2 text-xs text-[#5e7190]">
                  <span className={`rounded-full border px-2 py-1 ${record.isOpen ? "border-[#acd8c7] bg-[#e8f7ef] text-[#1c8f67]" : "border-[#d4dced]"}`}>
                    {record.isOpen ? "Abierta" : "Cerrada"}
                  </span>
                  <span className="rounded-full border border-[#d4dced] px-2 py-1">{getCategoryLabel(record.category)}</span>
                  <span className="rounded-full border border-[#d4dced] px-2 py-1">{formatAmount(record.amount, record.currency)}</span>
                  <span className="rounded-full border border-[#d4dced] px-2 py-1">Publicacion: {formatDate(record.publishDate)}</span>
                  <span className="rounded-full border border-[#d4dced] px-2 py-1">Cierre: {formatDate(record.closingDate)}</span>
                  <span className="rounded-full border border-[#d4dced] px-2 py-1">Fuente: {getSourceLabel(record.source)}</span>
                </div>

                <Link href={`/licitations/${record.id}`} className="mt-3 inline-flex text-sm font-semibold text-[#1f3f84]">
                  Ver detalle
                </Link>
              </article>
            ))
          )}
        </CardContent>
      </Card>
    </PageShell>
  );
}
