"use client";

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

export type MenuItem = {
  icon: React.ReactNode;
  label: string;
  href: string;
  roles: string[];
};

export const menuPrincipal: MenuItem[] = [
  { icon: <IconDashboard />, label: "Dashboard", href: "/dashboard", roles: ["admin"] },
  { icon: <IconCaja />, label: "Guías", href: "/guias", roles: ["admin", "recolector"] },
  { icon: <IconClientes />, label: "Clientes", href: "/clientes", roles: ["admin", "recolector"] },
  { icon: <IconRecibo />, label: "Recibos", href: "/recibos", roles: ["admin", "recolector"] },
  { icon: <IconCarro />, label: "Recibos de Carros", href: "/recibos-carros", roles: ["admin", "recolector"] },
  { icon: <IconCamion />, label: "Recolectores", href: "/recolectores", roles: ["admin"] },
  { icon: <IconEscanear />, label: "Escanear", href: "/escaneo", roles: ["admin", "entregas"] },
  { icon: <IconHeadset />, label: "Servicio al Cliente", href: "/servicio-cliente", roles: ["admin", "servicio"] },
  { icon: <IconPin />, label: "Rastreo", href: "/rastreo", roles: ["admin"] },
  { icon: <IconContenedor />, label: "Contenedores", href: "/contenedores", roles: ["admin"] },
  { icon: <IconPago />, label: "Pagos", href: "/pagos", roles: ["admin"] },
  { icon: <IconReporte />, label: "Reportes", href: "/reportes", roles: ["admin"] },
];

export const menuConfiguracion: MenuItem = {
  icon: <IconConfig />,
  label: "Configuración",
  href: "/configuraciones",
  roles: ["admin"],
};

export const menuUsuarios: MenuItem = {
  icon: <IconUsuarios />,
  label: "Usuarios",
  href: "/usuarios",
  roles: ["admin"],
};

interface SidebarProps {
  onItemClick?: () => void;
}

export default function Sidebar({ onItemClick }: SidebarProps) {
  const pathname = usePathname();
  const [user, setUser] = useState<SessionUser | null>(null);

  useEffect(() => {
    getCurrentUser().then(setUser).catch(() => setUser(null));
  }, []);

  const userTipo = user?.tipo || "";

  const visibleMenu = menuPrincipal.filter((item) =>
    item.roles.includes(userTipo)
  );

  const visibleConfig = menuConfiguracion.roles.includes(userTipo) ? menuConfiguracion : null;
  const visibleUsuarios = menuUsuarios.roles.includes(userTipo) ? menuUsuarios : null;

  const logout = async () => {
    try {
      await fetch("/cargoerp/api/logout", {
        method: "POST",
        credentials: "include",
      });
    } catch {}
    window.location.href = "/cargoerp/login";
  };

  const iniciales = (user?.nombre || "US")
    .split(" ")
    .map((p) => p[0])
    .join("")
    .slice(0, 2)
    .toUpperCase();

  return (
    <>
      {/* Logo */}
      <div className="flex items-center gap-2.5 px-4 pt-5 pb-4">
        <div className="relative flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-gradient-to-br from-blue-600 to-blue-800 shadow-md shadow-blue-900/40">
          <span className="text-sm font-black text-white">HCE</span>
        </div>
        <div className="min-w-0">
          <p className="text-xs font-black leading-tight tracking-wide text-[var(--text-primary)]">
            HONDURAS CARGO
          </p>
          <p className="text-[9px] font-black uppercase tracking-[0.15em] text-[var(--accent)]">
            Express
          </p>
        </div>
      </div>

      {/* Menú principal */}
      <nav className="flex-1 overflow-y-auto px-3 py-2">
        {visibleMenu.map((item) => {
          const activo = pathname === item.href || pathname.startsWith(item.href + "/");
          return (
            <Link
              key={item.href}
              href={item.href}
              onClick={onItemClick}
              className={`mb-1 flex items-center gap-2.5 rounded-lg px-3 py-2 text-xs font-semibold transition ${
                activo
                  ? "bg-gradient-to-r from-[var(--accent)] to-[var(--accent-hover)] text-white shadow-md shadow-[var(--accent)]/15"
                  : "text-[var(--text-secondary)] hover:bg-[var(--card-bg)] hover:text-[var(--text-primary)]"
              }`}
            >
              <span className="flex h-4 w-4 items-center justify-center">{item.icon}</span>
              {item.label}
            </Link>
          );
        })}

        {(visibleConfig || visibleUsuarios) && <div className="my-3 h-px bg-[var(--border)]" />}

        {visibleConfig && (
          <Link
            href={visibleConfig.href}
            onClick={onItemClick}
            className={`mb-1 flex items-center gap-2.5 rounded-lg px-3 py-2 text-xs font-semibold transition ${
              pathname === visibleConfig.href || pathname.startsWith(visibleConfig.href + "/")
                ? "bg-gradient-to-r from-[var(--accent)] to-[var(--accent-hover)] text-white shadow-md shadow-[var(--accent)]/15"
                : "text-[var(--text-secondary)] hover:bg-[var(--card-bg)] hover:text-[var(--text-primary)]"
            }`}
          >
            <span className="flex h-4 w-4 items-center justify-center">{visibleConfig.icon}</span>
            {visibleConfig.label}
          </Link>
        )}

        {visibleUsuarios && (
          <Link
            href={visibleUsuarios.href}
            onClick={onItemClick}
            className={`mb-1 flex items-center gap-2.5 rounded-lg px-3 py-2 text-xs font-semibold transition ${
              pathname === visibleUsuarios.href || pathname.startsWith(visibleUsuarios.href + "/")
                ? "bg-gradient-to-r from-[var(--accent)] to-[var(--accent-hover)] text-white shadow-md shadow-[var(--accent)]/15"
                : "text-[var(--text-secondary)] hover:bg-[var(--card-bg)] hover:text-[var(--text-primary)]"
            }`}
          >
            <span className="flex h-4 w-4 items-center justify-center">{visibleUsuarios.icon}</span>
            {visibleUsuarios.label}
          </Link>
        )}
      </nav>

      {/* Usuario */}
      <div className="border-t border-[var(--border)] p-3">
        <div className="mb-2 flex items-center gap-2.5 rounded-lg bg-[var(--card-bg)] px-3 py-2">
          <div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-gradient-to-br from-blue-600 to-blue-800 text-xs font-black text-white">
            {iniciales}
          </div>
          <div className="min-w-0 flex-1">
            <p className="truncate text-xs font-bold text-[var(--text-primary)]">
              {user?.nombre || "Usuario"}
            </p>
            <p className="text-[10px] text-[var(--text-muted)] uppercase">{userTipo || "—"}</p>
          </div>
        </div>

        <button
          type="button"
          onClick={logout}
          className="flex w-full items-center justify-center gap-1.5 rounded-lg border border-[var(--border)] bg-[var(--card-bg)] px-3 py-2 text-xs font-bold text-[var(--text-secondary)] transition hover:bg-red-500/10 hover:text-red-500"
        >
          <IconPower />
          Cerrar sesión
        </button>
      </div>
    </>
  );
}

/* =============================================================
   ICONOS
============================================================= */

function IconDashboard() {
  return (
    <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6" />
    </svg>
  );
}

function IconCaja() {
  return (
    <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4" />
    </svg>
  );
}

function IconClientes() {
  return (
    <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z" />
    </svg>
  );
}

function IconRecibo() {
  return (
    <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
    </svg>
  );
}

function IconCarro() {
  return (
    <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 10l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6" />
      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 17a2 2 0 11-4 0 2 2 0 014 0zm10 0a2 2 0 11-4 0 2 2 0 014 0z" />
    </svg>
  );
}

function IconCamion() {
  return (
    <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16V6a1 1 0 00-1-1H4a1 1 0 00-1 1v10a1 1 0 001 1h1m8-1a1 1 0 01-1 1H9m4-1V8a1 1 0 011-1h2.586a1 1 0 01.707.293l3.414 3.414a1 1 0 01.293.707V16a1 1 0 01-1 1h-1m-6-1a1 1 0 001 1h1M5 17a2 2 0 104 0m-4 0a2 2 0 114 0m6 0a2 2 0 104 0m-4 0a2 2 0 114 0" />
    </svg>
  );
}

function IconEscanear() {
  return (
    <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v1m6 11h2m-6 0h-2v4m0-11v3m0 0h.01M12 12h4.01M16 20h4M4 12h4m12 0h.01M5 8h2a1 1 0 001-1V5a1 1 0 00-1-1H5a1 1 0 00-1 1v2a1 1 0 001 1zm12 0h2a1 1 0 001-1V5a1 1 0 00-1-1h-2a1 1 0 00-1 1v2a1 1 0 001 1zM5 20h2a1 1 0 001-1v-2a1 1 0 00-1-1H5a1 1 0 00-1 1v2a1 1 0 001 1z" />
    </svg>
  );
}

function IconHeadset() {
  return (
    <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 11a7 7 0 01-7 7m0 0a7 7 0 01-7-7m7 7v4m0 0H8m4 0h4m-4-8a3 3 0 01-3-3V5a3 3 0 116 0v6a3 3 0 01-3 3z" />
    </svg>
  );
}

function IconPin() {
  return (
    <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z" />
      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 11a3 3 0 11-6 0 3 3 0 016 0z" />
    </svg>
  );
}

function IconContenedor() {
  return (
    <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10" />
    </svg>
  );
}

function IconPago() {
  return (
    <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 10h18M7 15h1m4 0h1m-7 4h12a3 3 0 003-3V8a3 3 0 00-3-3H6a3 3 0 00-3 3v8a3 3 0 003 3z" />
    </svg>
  );
}

function IconReporte() {
  return (
    <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" />
    </svg>
  );
}

function IconConfig() {
  return (
    <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" />
      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
    </svg>
  );
}

function IconUsuarios() {
  return (
    <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4.354a4 4 0 110 5.292M15 21H3v-1a6 6 0 0112 0v1zm0 0h6v-1a6 6 0 00-9-5.197M13 7a4 4 0 11-8 0 4 4 0 018 0z" />
    </svg>
  );
}

function IconPower() {
  return (
    <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5.636 5.636a9 9 0 1012.728 0M12 3v9" />
    </svg>
  );
}
