import { getServerSession } from "next-auth";
import { redirect } from "next/navigation";
import PrintToolbar from "@/components/kpis/PrintToolbar";
import { authOptions } from "@/lib/auth";
import { getDepartmentHomeRoute } from "@/lib/access-control";
import { canViewWeeklyKpiBoard, getWeeklyKpiBoard } from "@/lib/kpis/persistence";
import type { KpiRowStatus } from "@/lib/kpis/types";

export const dynamic = "force-dynamic";

const STATUS_LABELS: Record<KpiRowStatus, string> = {
  on_track: "En ruta",
  watch: "Seguimiento",
  risk: "Riesgo",
  no_score: "Sin score",
};

function formatDate(isoDate: string | null): string {
  if (!isoDate) {
    return "-";
  }

  const parsed = new Date(`${isoDate}T00:00:00.000Z`);
  return new Intl.DateTimeFormat("es-MX", {
    day: "2-digit",
    month: "short",
    year: "numeric",
    timeZone: "UTC",
  }).format(parsed);
}

export default async function DashboardPrintPage({
  searchParams,
}: {
  searchParams?: { weekStart?: string };
}) {
  const session = await getServerSession(authOptions);

  if (!session?.user) {
    redirect("/login");
  }

  const viewer = {
    role: session.user.role,
    department: session.user.department ?? null,
  };

  if (!canViewWeeklyKpiBoard(viewer)) {
    redirect(getDepartmentHomeRoute(viewer.department));
  }

  const board = await getWeeklyKpiBoard({
    weekStartInput: searchParams?.weekStart,
    viewer,
  });

  return (
    <div className="mx-auto max-w-[1100px] bg-white p-4 text-black md:p-6">
      <style>
        {`@media print {
          @page { size: A4 portrait; margin: 10mm; }
          body { background: white; }
        }`}
      </style>

      <PrintToolbar />

      <header className="mb-4 border-b border-gray-300 pb-3">
        <h1 className="text-2xl font-semibold">Weekly KPI Board</h1>
        <p className="mt-1 text-sm text-gray-600">
          Semana {board.weekStart} a {board.weekEnd} · Fuente: {board.source}
        </p>
        <p className="mt-1 text-sm text-gray-600">
          Actualizado: {board.lastUpdatedAt ? new Date(board.lastUpdatedAt).toLocaleString("es-MX") : "Sin actualización"}
        </p>
        <p className="mt-1 text-sm text-gray-600">
          Total KPIs: {board.summary.totalRows} · En ruta: {board.summary.onTrackPct.toFixed(1)}% · Riesgo: {board.summary.atRiskRows}
        </p>
        <p className="mt-1 text-sm text-gray-600">
          Cobertura: {board.coverage.mappedSections}/{board.coverage.totalSections} secciones mapeadas ({board.coverage.mappedPct.toFixed(1)}%)
        </p>
      </header>

      <section className="mb-4 grid grid-cols-2 gap-2 md:grid-cols-4">
        <article className="rounded border border-gray-300 p-2">
          <p className="text-xs text-gray-600">KPIs Totales</p>
          <p className="text-sm font-semibold">{board.summary.totalRows}</p>
        </article>
        <article className="rounded border border-gray-300 p-2">
          <p className="text-xs text-gray-600">En Ruta</p>
          <p className="text-sm font-semibold">{board.summary.onTrackPct.toFixed(1)}%</p>
        </article>
        <article className="rounded border border-gray-300 p-2">
          <p className="text-xs text-gray-600">Riesgo</p>
          <p className="text-sm font-semibold">{board.summary.atRiskRows}</p>
        </article>
        <article className="rounded border border-gray-300 p-2">
          <p className="text-xs text-gray-600">Vencen pronto</p>
          <p className="text-sm font-semibold">{board.summary.dueSoonRows}</p>
        </article>
      </section>

      <div className="space-y-4">
        {board.sections.map((section) => (
          <section key={section.id} className="break-inside-avoid rounded border border-gray-300 p-3">
            <header className="mb-2 flex items-center justify-between">
              <h2 className="text-base font-semibold">{section.rawSectionLabel}</h2>
              <p className="text-xs text-gray-600">{section.ownerTeamLabel || "Sin owner"}</p>
            </header>
            <div className="overflow-x-auto">
              <table className="min-w-full border-collapse text-xs">
                <thead>
                  <tr className="bg-gray-100 text-left">
                    <th className="border border-gray-300 px-2 py-1">Responsabilidad</th>
                    <th className="border border-gray-300 px-2 py-1">Objetivo / Indicador</th>
                    <th className="border border-gray-300 px-2 py-1">Quantity & Quality</th>
                    <th className="border border-gray-300 px-2 py-1">% Cumplimiento</th>
                    <th className="border border-gray-300 px-2 py-1">Fecha / Compromiso</th>
                    <th className="border border-gray-300 px-2 py-1">Estatus</th>
                  </tr>
                </thead>
                <tbody>
                  {section.rows.map((row) => (
                    <tr key={row.id}>
                      <td className="border border-gray-300 px-2 py-1 align-top">{row.responsibility}</td>
                      <td className="border border-gray-300 px-2 py-1 align-top">{row.objectiveIndicator || "-"}</td>
                      <td className="border border-gray-300 px-2 py-1 align-top">{row.quantityQuality || "-"}</td>
                      <td className="border border-gray-300 px-2 py-1 align-top">
                        {row.compliancePct !== null ? `${row.compliancePct.toFixed(1)}%` : row.compliance || "-"}
                      </td>
                      <td className="border border-gray-300 px-2 py-1 align-top">
                        <p>{row.dueCommitment || "-"}</p>
                        <p className="text-gray-600">{formatDate(row.dueDate)}</p>
                      </td>
                      <td className="border border-gray-300 px-2 py-1 align-top">{STATUS_LABELS[row.status]}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </section>
        ))}
      </div>
    </div>
  );
}
