"use client"

import { useState, useRef, useEffect } from "react"
import Link from "next/link"
import { useAuth } from "@/hooks/useAuth"
import { UserRole } from "@/types/auth"
import { Pill } from "lucide-react"

interface NavItem {
  label: string
  href: string
}

interface NavCategory {
  label: string
  icon: React.ReactNode
  items: NavItem[]
}

const Navbar = () => {
  const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false)
  const [activeDropdown, setActiveDropdown] = useState<string | null>(null)
  const timeoutRef = useRef<NodeJS.Timeout | null>(null)
  const { user } = useAuth()

  // Função para filtrar itens baseado no role do usuário
  const filterItemsByRole = (items: NavItem[], userRole?: UserRole): NavItem[] => {
    if (!userRole) return []
    
    // COLABORADOR: apenas Entregas
    if (userRole === UserRole.COLABORADOR) {
      return items.filter(item => item.href === '/entregas')
    }
    
    // ADMIN: todas exceto Usuários, Endereços, Empresas
    if (userRole === UserRole.ADMIN) {
      const restrictedPaths = ['/usuarios', '/enderecos', '/dashboard/empresa-novo']
      return items.filter(item => !restrictedPaths.includes(item.href))
    }
    
    // SUPERADMIN: todas as rotas
    return items
  }

  const allCategories: NavCategory[] = [
    {
      label: "Loja Virtual",
      icon: <Pill className="w-4 h-4" />,
      items: [
        { label: "Catálogo de Produtos", href: "/catalogo-produtos" },
        { label: "Produtos", href: "/produtos" },
        { label: "Categorias", href: "/categorias" },
        { label: "Carrinhos", href: "/carrinhos" },
        { label: "Pedidos", href: "/pedidos" },
        { label: "Entregas", href: "/entregas" },
        { label: "Faturas", href: "/faturas" },
        { label: "Pagamentos", href: "/pagamentos" },
        { label: "Laboratórios", href: "/laboratorios" },
        { label: "Usuários", href: "/usuarios" },
        { label: "Endereços", href: "/enderecos" },
        { label: "Empresas", href: "/dashboard/empresa-novo" },
      ],
    },
  ]

  // Filtrar categorias baseado no role do usuário
  const categories = allCategories.map(category => ({
    ...category,
    items: filterItemsByRole(category.items, user?.nivel as UserRole)
  })).filter(category => category.items.length > 0) // Remove categorias vazias

  const handleMouseEnter = (categoryLabel: string) => {
    if (timeoutRef.current) {
      clearTimeout(timeoutRef.current)
    }
    setActiveDropdown(categoryLabel)
  }

  const handleMouseLeave = () => {
    timeoutRef.current = setTimeout(() => {
      setActiveDropdown(null)
    }, 150) // 150ms delay antes de fechar
  }

  useEffect(() => {
    return () => {
      if (timeoutRef.current) {
        clearTimeout(timeoutRef.current)
      }
    }
  }, [])

  return (
    <nav className="bg-transparent">
      <div className="px-4">
        <div className="flex justify-center items-center h-12">
          {/* Desktop Navigation */}
          <div className="hidden md:flex items-center space-x-6">
            {categories.map((category) => (
              <div
                key={category.label}
                className="relative"
                onMouseEnter={() => handleMouseEnter(category.label)}
                onMouseLeave={handleMouseLeave}
              >
                <button
                  className="flex items-center space-x-1 text-gray-700 hover:text-blue-600 px-3 py-2 rounded-md text-sm font-medium transition-colors cursor-pointer"
                  role="button"
                  aria-haspopup="true"
                  aria-expanded={activeDropdown === category.label}
                >
                  <span>{category.icon}</span>
                  <span>{category.label}</span>
                  <svg className="w-4 h-4 ml-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
                  </svg>
                </button>
                {/* Dropdown Menu */}
                {activeDropdown === category.label && (
                  <div
                    className="absolute top-full left-0 mt-1 w-56 bg-white rounded-md shadow-lg border border-gray-200 z-50"
                    onMouseEnter={() => handleMouseEnter(category.label)}
                    onMouseLeave={handleMouseLeave}
                  >
                    <div className="py-1">
                      {category.items.map((item) => (
                        <Link
                          key={item.href}
                          href={item.href}
                          className="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-50 hover:text-blue-600 transition-colors cursor-pointer"
                        >
                          {item.label}
                        </Link>
                      ))}
                    </div>
                  </div>
                )}
              </div>
            ))}
          </div>
          {/* Mobile menu button */}
          <div className="md:hidden">
            <button
              onClick={() => setIsMobileMenuOpen(!isMobileMenuOpen)}
              className="text-gray-700 hover:text-blue-600 p-2 rounded-md transition-colors cursor-pointer"
            >
              <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                {isMobileMenuOpen ? (
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                ) : (
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6h16M4 12h16M4 18h16" />
                )}
              </svg>
            </button>
          </div>
        </div>
        {/* Mobile Navigation */}
        {isMobileMenuOpen && (
          <div className="md:hidden border-t border-gray-200 bg-white rounded-b-lg shadow-lg">
            <div className="py-2 space-y-1">
              {categories.map((category) => (
                <div key={category.label}>
                  <button
                    onClick={() => setActiveDropdown(activeDropdown === category.label ? null : category.label)}
                    className="w-full flex items-center justify-between px-3 py-2 text-gray-700 hover:bg-gray-50 hover:text-blue-600 transition-colors cursor-pointer"
                    role="button"
                    aria-haspopup="true"
                    aria-expanded={activeDropdown === category.label}
                  >
                    <div className="flex items-center space-x-2">
                      <span>{category.icon}</span>
                      <span className="font-medium">{category.label}</span>
                    </div>
                    <svg
                      className={`w-4 h-4 transition-transform ${
                        activeDropdown === category.label ? "rotate-180" : ""
                      }`}
                      fill="none"
                      stroke="currentColor"
                      viewBox="0 0 24 24"
                    >
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
                    </svg>
                  </button>
                  {/* Mobile Dropdown */}
                  {activeDropdown === category.label && (
                    <div className="bg-gray-50">
                      {category.items.map((item) => (
                        <Link
                          key={item.href}
                          href={item.href}
                          className="block px-8 py-2 text-sm text-gray-600 hover:text-blue-600 transition-colors cursor-pointer"
                          onClick={() => setIsMobileMenuOpen(false)}
                        >
                          {item.label}
                        </Link>
                      ))}
                    </div>
                  )}
                </div>
              ))}
            </div>
          </div>
        )}
      </div>
    </nav>
  )
}

export default Navbar
