"use client";

import Link from "next/link";
import { usePathname } from "next/navigation";
import { useEffect, useState } from "react";
import {
  getCurrentUser,
  SessionUser,
} from "../lib/session-client";

type MenuItem = {
  icon: string;
  text: string;
  href: string;
  roles?: string[];
};

const MENU_BASE: MenuItem[] = [
  {
    icon: "🏠",
    text: "Dashboard",
    href: "/dashboard",
    roles: ["admin", "usuario"],
  },
  {
    icon: "📦",
    text: "Guías",
    href: "/guias",
    roles: ["admin", "usuario", "recolector", "entregas"],
  },
  {
    icon: "🧾",
    text: "Recibos",
    href: "/recibos",
    roles: ["admin", "usuario", "recolector"],
  },
  {
    icon: "👥",
    text: "Clientes",
    href: "/clientes",
    roles: ["admin", "usuario", "recolector"],
  },
  {
    icon: "🚚",
    text: "Recolectores",
    href: "/recolectores",
    roles: ["admin", "usuario"],
  },
  {
    icon: "📷",
    text: "Escanear",
    href: "/escaneo",
    roles: ["admin", "usuario", "entregas"],
  },
  {
    icon: "📍",
    text: "Rastreo",
    href: "/rastreo",
    roles: ["admin", "usuario"],
  },
  {
    icon: "🚢",
    text: "Contenedores",
    href: "/contenedores",
    roles: ["admin", "usuario"],
  },
  {
    icon: "💰",
    text: "Pagos",
    href: "/pagos",
    roles: ["admin", "usuario"],
  },
  {
    icon: "📊",
    text: "Reportes",
    href: "/reportes",
    roles: ["admin", "usuario"],
  },
  {
    icon: "⚙️",
    text: "Configuraciones",
    href: "/configuraciones",
    roles: ["admin", "usuario"],
  },
  {
    icon: "🔐",
    text: "Usuarios",
    href: "/usuarios",
    roles: ["admin"],
  },
];

function MenuLink({
  item,
  activo,
  onClick,
}: {
  item: MenuItem;
  activo: boolean;
  onClick?: () => void;
}) {
  return (
    <Link
      key={item.href}
      href={item.href}
      onClick={onClick}
      className={`
        flex
        items-center
        gap-3
        rounded-xl
        px-4
        py-3
        text-sm
        font-medium
        transition
        ${
          activo
            ? "bg-orange-500 text-white shadow-lg"
            : "text-slate-300 hover:bg-slate-800 hover:text-white"
        }
      `}
    >
      <span className="text-xl">
        {item.icon}
      </span>

      <span>{item.text}</span>
    </Link>
  );
}

export default function Sidebar() {
  const pathname = usePathname();
  const [abierto, setAbierto] = useState(false);
  const [usuario, setUsuario] =
    useState<SessionUser | null>(null);
  const [cargando, setCargando] =
    useState(true);

  useEffect(() => {
    getCurrentUser()
      .then((u) => {
        setUsuario(u);
      })
      .finally(() => {
        setCargando(false);
      });
  }, []);

  const tipoUsuario =
    usuario?.tipo || "";

  const menuFiltrado =
    MENU_BASE.filter((item) => {
      if (!item.roles) {
        return true;
      }

      return item.roles.includes(
        tipoUsuario
      );
    });

  return (
    <>
      {/* Barra superior móvil */}
      <header
        className="
          fixed
          left-0
          right-0
          top-0
          z-40
          flex
          h-16
          items-center
          justify-between
          border-b
          border-slate-800
          bg-[#0b1220]
          px-4
          text-white
          md:hidden
        "
      >
        <button
          type="button"
          onClick={() =>
            setAbierto(true)
          }
          className="rounded-xl p-2 hover:bg-slate-800"
          aria-label="Abrir menú"
        >
          <svg
            className="h-6 w-6"
            fill="none"
            viewBox="0 0 24 24"
            stroke="currentColor"
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth={2}
              d="M4 6h16M4 12h16M4 18h16"
            />
          </svg>
        </button>

        <div className="flex items-center gap-2">
          <span className="text-xl">🚚</span>
          <span className="text-sm font-bold">
            Honduras Cargo
          </span>
        </div>

        <div className="w-8" />
      </header>

      {/* Overlay móvil */}
      {abierto && (
        <div
          className="fixed inset-0 z-40 bg-black/60 md:hidden"
          onClick={() =>
            setAbierto(false)
          }
        />
      )}

      {/* Sidebar */}
      <aside
        className={`
          fixed
          left-0
          top-0
          z-50
          flex
          h-screen
          w-72
          flex-col
          border-r
          border-slate-800
          bg-[#0b1220]
          text-white
          transition-transform
          duration-300
          ease-in-out
          md:translate-x-0
          ${
            abierto
              ? "translate-x-0"
              : "-translate-x-full"
          }
        `}
      >
        <div className="flex items-center justify-between border-b border-slate-800 p-5">
          <div>
            <h1 className="text-lg font-bold">
              🚚 Honduras Cargo
            </h1>

            <p className="mt-0.5 text-xs text-slate-400">
              Express
            </p>
          </div>

          <button
            type="button"
            onClick={() =>
              setAbierto(false)
            }
            className="rounded-xl p-2 hover:bg-slate-800 md:hidden"
            aria-label="Cerrar menú"
          >
            <svg
              className="h-5 w-5"
              fill="none"
              viewBox="0 0 24 24"
              stroke="currentColor"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M6 18L18 6M6 6l12 12"
              />
            </svg>
          </button>
        </div>

        <nav className="flex-1 overflow-y-auto p-3">
          <p className="mb-2 px-3 text-xs font-semibold uppercase tracking-wider text-slate-500">
            Menú principal
          </p>

          <div className="space-y-1">
            {cargando ? (
              <div className="px-3 py-4 text-sm text-slate-400">
                Cargando menú...
              </div>
            ) : (
              menuFiltrado.map((item) => {
                const activo =
                  pathname === item.href ||
                  pathname.startsWith(
                    `${item.href}/`
                  );

                return (
                  <MenuLink
                    key={item.href}
                    item={item}
                    activo={activo}
                    onClick={() =>
                      setAbierto(false)
                    }
                  />
                );
              })
            )}
          </div>
        </nav>

        <div className="space-y-3 border-t border-slate-800 p-4">
          {usuario && (
            <div className="rounded-xl bg-slate-800 p-3">
              <p className="text-sm font-semibold">
                {usuario.nombre || usuario.usuario}
              </p>

              <p className="mt-0.5 text-xs text-slate-400">
                {usuario.usuario}
              </p>
            </div>
          )}

          <div className="rounded-xl bg-slate-800/50 p-3">
            <p className="text-sm font-semibold">
              Honduras Cargo Express
            </p>

            <p className="mt-0.5 text-xs text-slate-400">
              Sistema de gestión
            </p>
          </div>
        </div>
      </aside>
    </>
  );
}
