"use client";

import Link from "next/link";
import { usePathname } from "next/navigation";
import {
  Factory,
  ClipboardList,
  LineChart,
  Settings2,
  Calculator,
  ArrowLeft,
} from "lucide-react";
import { cn } from "@/lib/utils";
import { usePuede, useSesion } from "./sesion-proveedor";
import { Skeleton } from "@/components/ui/skeleton";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";

const SECCIONES = [
  { href: "/", etiqueta: "Órdenes", icono: ClipboardList },
  { href: "/pronostico", etiqueta: "Pronóstico", icono: LineChart },
  { href: "/tarifas", etiqueta: "Tarifas", icono: Calculator },
  { href: "/lineas", etiqueta: "Líneas", icono: Settings2 },
];

/**
 * La puerta de salida.
 *
 * ⚠️ No es un detalle: este módulo se abre DESDE el Back Office y no tiene login propio,
 * así que quien entra y quiere volver no tiene botón de atrás que sirva —la URL de
 * entrada traía el token y ya se limpió— ni se sabe la dirección del Back Office de
 * memoria. Sin esto la única salida es cerrar la pestaña.
 *
 * La dirección la manda mbinv al emitir la sesión, porque cada cliente vive en una ruta
 * distinta. Si no vino, no se pinta nada: un enlace roto es peor que ninguno.
 */
function VolverAlBackOffice({ href }: { href: string | null }) {
  if (!href) return null;

  return (
    <a
      href={href}
      className="flex shrink-0 items-center gap-1.5 rounded-md px-2 py-1.5 text-sm text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
      title="Volver al Back Office"
    >
      <ArrowLeft className="size-4" />
      <span className="hidden md:inline">Back Office</span>
    </a>
  );
}

function saludo(): string {
  const hora = new Date().getHours();
  if (hora < 12) return "Buenos días";
  if (hora < 19) return "Buenas tardes";
  return "Buenas noches";
}

export function Marco({ children }: { children: React.ReactNode }) {
  const ruta = usePathname();
  const estado = useSesion();
  // La sesión no distingue el alcance de `ver` (global o por línea): la entrada se ofrece a quien puede ver y el servidor decide;
  // la pantalla de tarifas muestra el error de carga si responde 403.
  const puedeTarifas = usePuede("ver");
  const sesion = estado.fase === "lista" ? estado.sesion : null;

  return (
    <div className="flex min-h-screen flex-col bg-muted/30">
      <header className="sticky top-0 z-30 border-b bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80">
        <div className="mx-auto flex h-14 max-w-7xl items-center gap-3 px-4 sm:gap-6">
          <Link
            href="/"
            className="flex shrink-0 items-center gap-2 font-semibold transition-opacity hover:opacity-80"
          >
            <Factory className="size-5 text-primary" />
            <span className="hidden sm:inline">Producción</span>
          </Link>

          <nav className="flex min-w-0 items-center gap-1 overflow-x-auto">
            {SECCIONES.filter((s) => "/tarifas" !== s.href || puedeTarifas).map(({ href, etiqueta, icono: Icono }) => {
              const activa =
                href === "/"
                  ? ruta === "/" || ruta.startsWith("/ordenes")
                  : ruta.startsWith(href);
              return (
                <Link
                  key={href}
                  href={href}
                  className={cn(
                    "flex shrink-0 items-center gap-2 rounded-md px-3 py-1.5 text-sm transition-colors",
                    activa
                      ? "bg-primary/10 font-medium text-primary"
                      : "text-muted-foreground hover:bg-muted hover:text-foreground",
                  )}
                >
                  <Icono className="size-4" />
                  {etiqueta}
                </Link>
              );
            })}
          </nav>

          <div className="ml-auto flex shrink-0 items-center gap-1">
            <VolverAlBackOffice href={sesion?.retorno ?? null} />

            {sesion ? (
              <div className="flex items-center gap-2 px-2 py-1">
                <span className="hidden text-sm text-muted-foreground lg:inline">
                  {saludo()},
                </span>
                <span className="text-sm font-medium">{sesion.nombre}</span>
              </div>
            ) : null}
          </div>
        </div>
      </header>

      <main className="mx-auto w-full max-w-7xl flex-1 px-4 py-6">
        {estado.fase === "cargando" ? (
          <div className="space-y-3">
            <Skeleton className="h-9 w-64" />
            <Skeleton className="h-64 w-full" />
          </div>
        ) : estado.fase === "sin-sesion" ? (
          <Alert variant="destructive" className="mx-auto max-w-2xl">
            <AlertTitle>No hay sesión</AlertTitle>
            <AlertDescription>
              <p>{estado.motivo}</p>
              <p className="mt-2 text-sm">
                Entrá al Back Office y abrí <strong>Producción (nuevo)</strong> desde el
                menú de Movimientos. La sesión dura ocho horas.
              </p>
            </AlertDescription>
          </Alert>
        ) : (
          children
        )}
      </main>

      <footer className="border-t bg-background/50">
        <div className="mx-auto flex max-w-7xl flex-wrap items-center justify-between gap-2 px-4 py-3 text-xs text-muted-foreground">
          <span>Producción — MacroBase</span>
          {sesion?.retorno ? (
            <a href={sesion.retorno} className="hover:text-foreground hover:underline">
              Volver al Back Office
            </a>
          ) : null}
        </div>
      </footer>
    </div>
  );
}
