"use client";

import Link from "next/link";
import { useEffect } from "react";
import { usePathname } from "next/navigation";
import {
  LayoutDashboard,
  Calculator,
  CalendarDays,
  ClipboardList,
  Workflow,
  FileText,
  Handshake,
  Scissors,
  Wallet,
  BarChart3,
  MessageCircle,
  Settings,
  BookUser,
  BookOpen,
  ListTodo,
  PencilRuler,
  type LucideIcon,
} from "lucide-react";
import { cn } from "@/lib/cn";
import { useAuthStore } from "@/lib/store/useAuthStore";
import { useNavAlerts, navBadgesFor } from "@/lib/store/useNavAlerts";
import type { UserRole } from "@/lib/types";
import { hasModulePermission, type PermissionModule } from "@/lib/permissions/domain";

interface MobileNavItem {
  href: string;
  label: string;
  icon: LucideIcon;
  module: PermissionModule;
  roles?: UserRole[];
}

const ITEMS: MobileNavItem[] = [
  { href: "/inicio",        label: "Inicio",     icon: LayoutDashboard, module: "inicio" },
  { href: "/chatwoot",      label: "Chat",        icon: MessageCircle,   module: "chatwoot" },
  { href: "/disenador",     label: "Diseñador",   icon: PencilRuler,     module: "disenador", roles: ["admin"] },
  { href: "/calculadora",   label: "Calc",        icon: Calculator,      module: "calculadora" },
  { href: "/crm",           label: "CRM",         icon: Handshake,       module: "crm" },
  { href: "/presupuestos",  label: "Presu",       icon: FileText,        module: "presupuestos" },
  { href: "/pedidos",       label: "Pedidos",     icon: ClipboardList,   module: "pedidos" },
  { href: "/pipeline",      label: "Pipeline",    icon: Workflow,        module: "pipeline" },
  { href: "/cortes",        label: "Cortes",      icon: Scissors,        module: "cortes" },
  { href: "/calendario",    label: "Agenda",      icon: CalendarDays,    module: "calendario" },
  { href: "/tareas",        label: "Tareas",      icon: ListTodo,        module: "tareas" },
  { href: "/caja",          label: "Caja",        icon: Wallet,          module: "caja" },
  { href: "/contactos",     label: "Contactos",   icon: BookUser,        module: "clientes" },
  { href: "/catalogo",      label: "Catálogo",    icon: BookOpen,        module: "catalogo" },
  { href: "/reportes",      label: "Reportes",    icon: BarChart3,       module: "reportes" },
  { href: "/configuracion", label: "Config",      icon: Settings,        module: "configuracion" },
];

export default function MobileNav() {
  const pathname = usePathname();
  const user = useAuthStore((s) => s.user);
  const permissions = useAuthStore((s) => s.permissions);
  const crmVencidas = useNavAlerts((s) => s.crmVencidas);
  const crmHoy = useNavAlerts((s) => s.crmHoy);
  const pedidosVencidos = useNavAlerts((s) => s.pedidosVencidos);
  const pedidosHoy = useNavAlerts((s) => s.pedidosHoy);
  const tareasVencidas = useNavAlerts((s) => s.tareasVencidas);
  const tareasHoy = useNavAlerts((s) => s.tareasHoy);
  const refreshAlerts = useNavAlerts((s) => s.refresh);
  useEffect(() => {
    refreshAlerts();
  }, [refreshAlerts]);
  const items = ITEMS.filter((i) => {
    if (!user) return false;
    if (process.env.NEXT_PUBLIC_DEMO_MODE === "true" && i.module === "chatwoot") return false;
    if (i.roles && !i.roles.includes(user.role)) return false;
    return hasModulePermission(user.role, i.module, "can_view", permissions);
  });

  return (
    <nav className="md:hidden fixed bottom-0 inset-x-0 z-30 bg-surface border-t border-line overflow-x-auto">
      <div className="flex min-w-max px-2 py-1.5 gap-1">
        {items.map((item) => {
          const Icon = item.icon;
          const active = pathname === item.href || pathname.startsWith(item.href + "/");
          const badges = navBadgesFor(item.href, { crmVencidas, crmHoy, pedidosVencidos, pedidosHoy, tareasVencidas, tareasHoy });
          return (
            <Link
              key={item.href}
              href={item.href}
              className={cn(
                "relative w-16 h-12 rounded-lg flex flex-col items-center justify-center gap-0.5 text-[11px] font-medium",
                active ? "bg-brand-soft text-brand-dark" : "text-faint hover:text-ink",
              )}
            >
              {badges.length > 0 && (
                <span className="absolute top-0.5 right-1 flex gap-0.5">
                  {badges.map((b, i) => (
                    <span
                      key={i}
                      className={cn(
                        "min-w-[14px] rounded-full px-0.5 text-center text-[9px] font-bold leading-[14px] text-white",
                        b.tone === "red" ? "bg-red-500" : "bg-orange-500",
                      )}
                    >
                      {b.n}
                    </span>
                  ))}
                </span>
              )}
              <Icon size={17} />
              <span className="leading-none">{item.label}</span>
            </Link>
          );
        })}
      </div>
    </nav>
  );
}
