import { useEffect, useRef, useState } from 'react'
import { Link, useLocation } from 'react-router-dom'
import { useAuth } from '../context/AuthContext'

const navItems = [
    { path: '/dashboard', label: 'Início' },
    { path: '/dashboard/users', label: 'Usuários' },
    { path: '/dashboard/companies', label: 'Empresas' },
    { path: '/dashboard/products', label: 'Produtos' },
    { path: '/dashboard/orders', label: 'Pedidos' },
    { path: '/dashboard/reviews', label: 'Avaliações' },
    { path: '/dashboard/logistics', label: 'Logística' },
]

export function Header() {
    const { user, logout } = useAuth()
    const location = useLocation()
    const [isOpen, setIsOpen] = useState(false)
    const dropdownRef = useRef<HTMLDivElement>(null)

    useEffect(() => {
        const handleClickOutside = (event: MouseEvent) => {
            if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
                setIsOpen(false)
            }
        }

        document.addEventListener('mousedown', handleClickOutside)
        return () => {
            document.removeEventListener('mousedown', handleClickOutside)
        }
    }, [])

    return (
        <header className="bg-gradient-to-r from-blue-900 to-blue-700 text-white shadow-lg">
            <div className="mx-auto max-w-7xl px-4">
                <div className="flex h-16 items-center justify-between">
                    {/* Logo */}
                    <Link to="/dashboard" className="flex items-center gap-2">
                        <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-white/20">
                            <span className="text-xl font-bold">💊</span>
                        </div>
                        <span className="text-xl font-bold">SaveInMed</span>
                    </Link>

                    {/* Navigation */}
                    <nav className="hidden md:flex items-center gap-1">
                        {navItems.map((item) => {
                            const isActive = location.pathname === item.path ||
                                (item.path !== '/dashboard' && location.pathname.startsWith(item.path))
                            return (
                                <Link
                                    key={item.path}
                                    to={item.path}
                                    className={`px-4 py-2 rounded-lg text-sm font-medium transition-all ${isActive
                                        ? 'bg-white/20 text-white'
                                        : 'text-white/80 hover:bg-white/10 hover:text-white'
                                        }`}
                                >
                                    {item.label}
                                </Link>
                            )
                        })}
                    </nav>

                    {/* User info */}
                    <div className="relative flex items-center gap-4" ref={dropdownRef}>
                        <button
                            onClick={() => setIsOpen((prev) => !prev)}
                            className="flex items-center gap-2 rounded-lg bg-white/10 px-3 py-2 text-sm font-medium text-white transition-colors hover:bg-white/20"
                        >
                            <div className="flex h-8 w-8 items-center justify-center rounded-full bg-white/20 text-xs font-semibold">
                                {(user?.name || 'U').charAt(0).toUpperCase()}
                            </div>
                            <div className="hidden sm:flex flex-col items-start">
                                <span className="text-sm font-medium">{user?.name}</span>
                                <span className="text-xs text-white/70 capitalize">{user?.role}</span>
                            </div>
                            <svg
                                className="h-4 w-4 text-white/70"
                                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>

                        {isOpen && (
                            <div className="absolute right-0 top-full mt-2 w-48 rounded-lg bg-white py-2 text-sm text-gray-700 shadow-lg">
                                <Link
                                    to="/dashboard/profile"
                                    className="block px-4 py-2 hover:bg-gray-100"
                                    onClick={() => setIsOpen(false)}
                                >
                                    Meu perfil
                                </Link>
                                <button
                                    onClick={logout}
                                    className="w-full px-4 py-2 text-left text-red-600 hover:bg-red-50"
                                >
                                    Sair
                                </button>
                            </div>
                        )}
                    </div>
                </div>
            </div>

            {/* Mobile Navigation */}
            <nav className="md:hidden border-t border-white/20 px-4 py-2 flex gap-2 overflow-x-auto">
                {navItems.map((item) => {
                    const isActive = location.pathname === item.path
                    return (
                        <Link
                            key={item.path}
                            to={item.path}
                            className={`whitespace-nowrap px-3 py-1.5 rounded-lg text-sm font-medium ${isActive ? 'bg-white/20' : 'text-white/80'
                                }`}
                        >
                            {item.label}
                        </Link>
                    )
                })}
            </nav>
        </header>
    )
}
