"use client"

import { useState } from "react"
import Link from "next/link"
import { useAuth } from "@/hooks/useAuth"
import { UserRole } from "@/types/auth"
import { Building2 } from "lucide-react"

interface NavItem {
  label: string
  href: string
}

const Navbar = () => {
  const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false)
  const [activeDropdown, setActiveDropdown] = useState<string | 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 allItems: NavItem[] = [
    { 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 itens baseado no role do usuário
  const items = filterItemsByRole(allItems, user?.nivel as UserRole)

  // Se não há itens visíveis para o usuário, não renderiza nada
  if (items.length === 0) return null

  return (
    <nav className="bg-transparent">
      <div className="px-4">
        <div className="flex justify-center items-center h-12">
          {/* 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">
              <div>
                <button
                  onClick={() => setActiveDropdown(activeDropdown === "loja" ? null : "loja")}
                  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 === "loja"}
                >
                  <div className="flex items-center space-x-2">
                    <Building2 className="w-4 h-4" />
                    <span className="font-medium">Loja Virtual</span>
                  </div>
                  <svg
                    className={`w-4 h-4 transition-transform ${
                      activeDropdown === "loja" ? "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 === "loja" && (
                  <div className="bg-gray-50">
                    {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
