import { useState } from 'react'
import { Link, useLocation } from 'react-router-dom'
import { useAuth, UserRole } from '@/context/AuthContext'
import { Menu, X } from 'lucide-react'
import logoImg from '../assets/logo.png'

interface SidebarItem {
  label: string
  path: string
  icon: JSX.Element
  roles: UserRole[]
}

/**
 * Mapa de permissões por role:
 *
 * admin      → usa o Header horizontal, sem Sidebar
 * owner      → Meu Painel, Estoque, Produtos, Pedidos, Carteira, Equipe, Config. Entrega
 * seller     → Meu Painel, Estoque, Produtos, Pedidos, Carteira, Equipe, Config. Entrega
 * employee   → usa Header horizontal sem Sidebar (reescrito)
 * delivery   → usa Header horizontal sem Sidebar (reescrito)
 * customer   → Sidebar não é usado
 */
const menuItems: SidebarItem[] = [
  // ─── Owner / Seller ───────────────────────────────────
  {
    label: 'Meu Painel',
    path: '/seller',
    icon: (
      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2}
          d="M3 12l2-4m0 0l7-4 7 4M5 8v10a1 1 0 001 1h12a1 1 0 001-1V8m-9 4v4m0 0h4m-4 0V9" />
      </svg>
    ),
    roles: ['owner', 'seller'],
  },
  {
    label: 'Estoque',
    path: '/inventory',
    icon: (
      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2}
          d="M20 7l-8-4-8 4m0 0l8 4m-8-4v10l8 4m0-10l8 4m-8-4v10M4 12v5a2 2 0 002 2h12a2 2 0 002-2v-5" />
      </svg>
    ),
    roles: ['owner', 'seller'],
  },
  {
    label: 'Buscar Produtos',
    path: '/search',
    icon: (
      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2}
          d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
      </svg>
    ),
    roles: ['owner', 'seller'],
    // employee NÃO vê Produtos no sidebar (ele tem o próprio dashboard)
  },
  {
    label: 'Pedidos',
    path: '/orders',
    icon: (
      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2}
          d="M16 11V7a4 4 0 00-8 0v4M5 9h14l1 12H4L5 9z" />
      </svg>
    ),
    roles: ['owner', 'seller'],
  },
  {
    label: 'Carteira',
    path: '/wallet',
    icon: (
      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2}
          d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
      </svg>
    ),
    roles: ['owner', 'seller'],
  },
  {
    label: 'Equipe',
    path: '/team',
    icon: (
      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2}
          d="M17 20h5v-2a3 3 0 00-5.856-1.487M15 10a3 3 0 11-6 0 3 3 0 016 0zM6 20a9 9 0 0118 0v2h2v-2a11 11 0 00-22 0v2h2v-2z" />
      </svg>
    ),
    roles: ['owner', 'seller'],
  },
  {
    label: 'Config. de Entrega',
    path: '/shipping-settings',
    icon: (
      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <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" />
      </svg>
    ),
    roles: ['owner', 'seller'],
  },
]

interface SidebarProps {
  /** @deprecated — passe userRole via prop ou deixe o Sidebar ler do useAuth automaticamente */
  userRole?: UserRole
  collapsed?: boolean
  onNavigate?: () => void
}

export function Sidebar({ userRole: userRoleProp, collapsed: initialCollapsed, onNavigate }: SidebarProps) {
  const [collapsed, setCollapsed] = useState(initialCollapsed || false)
  const location = useLocation()
  const { user } = useAuth()

  // Prioriza a prop (legado), mas usa a role do contexto se não houver prop
  const role: UserRole = userRoleProp ?? user?.role ?? 'seller'

  // Filtra itens com base na role real
  const visibleItems = menuItems.filter(item => item.roles.includes(role))

  // Se não há itens visíveis para esta role, não renderiza o Sidebar
  if (visibleItems.length === 0) return null

  return (
    <>
      {/* Mobile toggle button */}
      <button
        onClick={() => setCollapsed(!collapsed)}
        className="md:hidden fixed top-4 right-4 z-50 p-2 text-white rounded-lg hover:opacity-80"
        style={{ backgroundColor: '#0F4C81' }}
      >
        {collapsed ? <Menu className="w-6 h-6" /> : <X className="w-6 h-6" />}
      </button>

      {/* Sidebar */}
      <aside
        className={`${collapsed ? 'hidden' : 'block'
          } md:block fixed md:relative left-0 top-0 h-screen md:h-auto w-64 text-white overflow-y-auto transition-all duration-300 z-40 md:z-auto`}
        style={{ backgroundColor: '#0F4C81' }}
      >
        <div className="p-6 pt-16 md:pt-6">
          {/* Logo */}
          <div className="mb-8 flex items-center gap-2">
            <img src={logoImg} alt="SaveInMed" className="h-8 w-auto" />
            <span className="text-lg font-bold">SaveInMed</span>
          </div>

          {/* Role badge */}
          <div className="mb-5 px-3 py-1.5 rounded-full text-xs font-semibold bg-white/15 text-white/90 w-fit capitalize">
            {role === 'owner' ? 'Proprietário' : role === 'seller' ? 'Vendedor' : role}
          </div>

          <nav className="space-y-1">
            {visibleItems.map((item) => {
              const isActive = location.pathname === item.path ||
                (item.path !== '/' && location.pathname.startsWith(item.path))

              return (
                <Link
                  key={item.path}
                  to={item.path}
                  onClick={() => {
                    onNavigate?.()
                    setCollapsed(true)
                  }}
                  className={`flex items-center gap-3 px-4 py-3 rounded-lg transition-all ${isActive
                      ? 'bg-white/20 text-white shadow'
                      : 'text-white/75 hover:text-white hover:bg-white/10'
                    }`}
                >
                  {item.icon}
                  <span className="text-sm font-medium">{item.label}</span>
                </Link>
              )
            })}
          </nav>
        </div>
      </aside>

      {/* Backdrop for mobile */}
      {!collapsed && (
        <div
          className="md:hidden fixed inset-0 bg-black/50 z-30"
          onClick={() => setCollapsed(true)}
        />
      )}
    </>
  )
}
