"use client";

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

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

// En la demo pública ocultamos Mensajería: usaría el Chatwoot real con chats de
// clientes reales. La privacidad se garantiza además por env (sin token en el demo).
const DEMO = process.env.NEXT_PUBLIC_DEMO_MODE === "true";

const NAV: NavItem[] = [
  { href: "/inicio",      label: "Inicio",      icon: LayoutDashboard, module: "inicio" },
  { href: "/chatwoot",    label: "Mensajería",  icon: MessageCircle, module: "chatwoot" },
  { href: "/disenador",   label: "Diseñador",   icon: PencilRuler, module: "disenador", roles: ["admin"] },
  { href: "/calculadora", label: "Calculadora", icon: Calculator, module: "calculadora" },
  { href: "/crm",         label: "CRM",         icon: Handshake, module: "crm" },
  { href: "/presupuestos", label: "Presupuestos", 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: "Calendario",  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: "Configuración", icon: Settings, module: "configuracion" },
];

export default function Sidebar() {
  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 = NAV.filter((i) => {
    if (!user) return false;
    if (DEMO && 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 (
    <aside className="hidden md:flex md:flex-col w-60 bg-surface border-r border-line h-dvh sticky top-0">
      <div className="flex items-center px-5 py-5 border-b border-line">
        <img
          src="/logo-fibromuebles.png"
          alt="Fibromuebles"
          className="h-8 w-auto max-w-[180px]"
        />
      </div>

      <nav className="flex-1 px-3 py-4 flex flex-col 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 flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm font-medium transition-colors",
                active
                  ? "text-brand-dark"
                  : "text-ink-soft hover:text-ink hover:bg-canvas",
              )}
            >
              {active && (
                <motion.div
                  layoutId="sidebar-active"
                  className="absolute inset-0 bg-brand-soft rounded-lg -z-10"
                  transition={{ type: "spring", stiffness: 380, damping: 30 }}
                />
              )}
              <Icon size={18} />
              {item.label}
              {badges.length > 0 && (
                <span className="ml-auto flex items-center gap-1">
                  {badges.map((b, i) => (
                    <span
                      key={i}
                      className={cn(
                        "min-w-[18px] rounded-full px-1 text-center text-[10px] font-bold leading-[18px] text-white",
                        b.tone === "red" ? "bg-red-500" : "bg-orange-500",
                      )}
                    >
                      {b.n}
                    </span>
                  ))}
                </span>
              )}
            </Link>
          );
        })}
      </nav>

      <div className="px-5 py-4 border-t border-line text-xs text-faint">
        v0.6.0 — Apps completas
      </div>
    </aside>
  );
}
