
import React, { useState, useEffect, useRef } from 'react';
import { Menu, X, Code2, User, LogIn, UserPlus, LogOut, LayoutDashboard, ShieldAlert, Crown } from 'lucide-react';
import { Link, useLocation, useNavigate } from 'react-router-dom';
import { Button } from './Button';
import { useAuth } from '../context/AuthContext';

export const Navbar: React.FC = () => {
  const [isOpen, setIsOpen] = useState(false);
  const [isProfileOpen, setIsProfileOpen] = useState(false);
  const [scrolled, setScrolled] = useState(false);
  const location = useLocation();
  const navigate = useNavigate();
  const profileRef = useRef<HTMLDivElement>(null);
  const { user, signOut, isAdmin } = useAuth();

  useEffect(() => {
    const handleScroll = () => {
      setScrolled(window.scrollY > 20);
    };
    window.addEventListener('scroll', handleScroll);
    
    // Close dropdown when clicking outside
    const handleClickOutside = (event: MouseEvent) => {
      if (profileRef.current && !profileRef.current.contains(event.target as Node)) {
        setIsProfileOpen(false);
      }
    };
    document.addEventListener('mousedown', handleClickOutside);

    return () => {
      window.removeEventListener('scroll', handleScroll);
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, []);

  useEffect(() => {
    setIsOpen(false);
    setIsProfileOpen(false);
  }, [location]);

  const handleLogout = async () => {
    await signOut();
    navigate('/');
    setIsProfileOpen(false);
  };

  // Helper to determine if a link is active based on hash or path
  const isActive = (path: string) => {
    if (path === '/') return location.pathname === '/' && !location.hash;
    if (path.startsWith('/#')) return location.hash === path.substring(1);
    return location.pathname === path;
  };

  const navLinks = [
    { name: 'Kezdőlap', path: '/' },
    { name: 'Szolgáltatások', path: '/#services' },
    { name: 'Referenciák', path: '/#references' },
    { name: 'Csomagok', path: '/#products' },
  ];

  const linkClass = (path: string) => `text-sm font-medium transition-colors hover:text-primary ${
    isActive(path) ? 'text-primary' : (
      !scrolled && location.pathname === '/' ? 'text-gray-100 hover:text-white' : 'text-gray-700'
    )
  }`;

  return (
    <nav className={`fixed w-full z-50 transition-all duration-300 ${scrolled ? 'bg-white/90 backdrop-blur-md shadow-md py-2' : 'bg-transparent py-4'}`}>
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div className="flex justify-between items-center h-16">
          {/* Logo */}
          <Link to="/" className="flex items-center space-x-2 group">
            <div className="p-2 bg-gradient-to-br from-primary to-secondary rounded-lg group-hover:shadow-lg transition-all duration-300">
              <Code2 className="h-6 w-6 text-white" />
            </div>
            <span className={`text-2xl font-bold bg-clip-text text-transparent bg-gradient-to-r from-primary to-secondary ${!scrolled && location.pathname === '/' ? 'text-white' : ''}`}>
              MotionWeb
            </span>
          </Link>

          {/* Desktop Navigation Links */}
          <div className="hidden md:flex items-center space-x-8">
            {navLinks.map((link) => (
              <Link
                key={link.path}
                to={link.path}
                className={linkClass(link.path)}
              >
                {link.name}
              </Link>
            ))}
          </div>

          {/* Right Side Actions */}
          <div className="flex items-center gap-4">
            {/* Desktop Order Button */}
            <div className="hidden md:block">
              <Link to="/#rendeles">
                <Button variant={!scrolled && location.pathname === '/' ? 'white' : 'primary'} size="sm">
                  Rendelés
                </Button>
              </Link>
            </div>

            {/* Profile Dropdown */}
            <div className="relative" ref={profileRef}>
              <button 
                onClick={() => setIsProfileOpen(!isProfileOpen)}
                className={`p-2 rounded-full transition-colors duration-300 flex items-center justify-center ${
                  !scrolled && location.pathname === '/' 
                    ? 'text-white hover:bg-white/10' 
                    : 'text-gray-700 hover:bg-gray-100'
                } ${user ? 'ring-2 ring-primary/20 bg-primary/5' : ''}`}
                aria-label="Felhasználói fiók"
              >
                <User className="w-6 h-6" />
                {isAdmin && (
                  <div className="absolute -top-1 -right-1 bg-white rounded-full p-0.5 shadow-sm border border-gray-100">
                    <Crown className="w-3.5 h-3.5 text-yellow-500 fill-yellow-500" />
                  </div>
                )}
              </button>

              {isProfileOpen && (
                <div className="absolute right-0 mt-3 w-64 bg-white rounded-xl shadow-2xl py-2 border border-gray-100 transform origin-top-right animate-fade-in z-50">
                  <div className="px-4 py-3 border-b border-gray-100 bg-gray-50/50">
                    <p className="text-sm font-semibold text-gray-900">Fiókom</p>
                    <p className="text-xs text-gray-500 truncate">{user ? user.email : 'Vendég felhasználó'}</p>
                  </div>
                  
                  <div className="py-2">
                    {user ? (
                      <>
                        <Link to="/dashboard" className="flex items-center px-4 py-2.5 text-sm text-gray-700 hover:bg-purple-50 hover:text-primary transition-colors">
                          <LayoutDashboard className="w-4 h-4 mr-3" /> Vezérlőpult
                        </Link>
                        
                        {isAdmin && (
                          <Link to="/admin" className="flex items-center px-4 py-2.5 text-sm text-red-600 hover:bg-red-50 hover:text-red-700 transition-colors font-semibold">
                            <ShieldAlert className="w-4 h-4 mr-3" /> Admin Felület
                          </Link>
                        )}
                        
                        <div className="border-t border-gray-100 my-1"></div>
                        <button onClick={handleLogout} className="w-full flex items-center px-4 py-2.5 text-sm text-red-600 hover:bg-red-50 transition-colors">
                          <LogOut className="w-4 h-4 mr-3" /> Kijelentkezés
                        </button>
                      </>
                    ) : (
                      <>
                        <Link to="/auth/login" className="flex items-center px-4 py-2.5 text-sm text-gray-700 hover:bg-purple-50 hover:text-primary transition-colors">
                          <LogIn className="w-4 h-4 mr-3" /> Bejelentkezés
                        </Link>
                        <Link to="/auth/register" className="flex items-center px-4 py-2.5 text-sm text-gray-700 hover:bg-purple-50 hover:text-primary transition-colors">
                          <UserPlus className="w-4 h-4 mr-3" /> Regisztráció
                        </Link>
                      </>
                    )}
                  </div>
                </div>
              )}
            </div>

            {/* Mobile Menu Toggle */}
            <div className="md:hidden">
              <button
                onClick={() => setIsOpen(!isOpen)}
                className={`p-2 rounded-md ${!scrolled && location.pathname === '/' ? 'text-white' : 'text-gray-700'}`}
              >
                {isOpen ? <X className="h-6 w-6" /> : <Menu className="h-6 w-6" />}
              </button>
            </div>
          </div>
        </div>
      </div>

      {/* Mobile Menu */}
      {isOpen && (
        <div className="md:hidden bg-white border-t border-gray-100 shadow-xl absolute w-full animate-fade-in">
          <div className="px-2 pt-2 pb-3 space-y-1 sm:px-3">
            {navLinks.map((link) => (
              <Link
                key={link.path}
                to={link.path}
                className={`block px-3 py-2 rounded-md text-base font-medium ${
                  isActive(link.path)
                    ? 'text-primary bg-purple-50'
                    : 'text-gray-700 hover:text-primary hover:bg-gray-50'
                }`}
              >
                {link.name}
              </Link>
            ))}
            <div className="pt-4 pb-2 px-3 space-y-3">
              <Link to="/#rendeles" className="block w-full">
                <Button fullWidth>Rendelés</Button>
              </Link>
              
              {!user && (
                <div className="grid grid-cols-2 gap-3 pt-2">
                   <Link to="/auth/login">
                     <Button variant="outline" fullWidth size="sm">Belépés</Button>
                   </Link>
                   <Link to="/auth/register">
                     <Button variant="secondary" fullWidth size="sm">Regisztráció</Button>
                   </Link>
                </div>
              )}
              
              {user && (
                <div className="pt-2 border-t border-gray-100">
                  <div className="px-1 py-2 flex items-center gap-3 mb-2">
                     <div className="w-8 h-8 rounded-full bg-primary/10 flex items-center justify-center text-primary">
                        <User className="w-4 h-4" />
                     </div>
                     <div className="overflow-hidden">
                        <p className="text-sm font-medium text-gray-900 truncate">{user.email}</p>
                        {isAdmin && <p className="text-[10px] text-red-500 font-bold uppercase">Adminisztrátor</p>}
                     </div>
                  </div>
                  <Link to="/dashboard" className="block w-full text-center py-2 text-sm font-medium text-gray-700 bg-gray-50 rounded-lg mb-2">
                    Vezérlőpult megnyitása
                  </Link>
                  {isAdmin && (
                    <Link to="/admin" className="block w-full text-center py-2 text-sm font-medium text-red-600 bg-red-50 rounded-lg mb-2 border border-red-100">
                       Admin Felület
                    </Link>
                  )}
                  <button onClick={handleLogout} className="block w-full text-center py-2 text-sm font-medium text-red-600 border border-red-100 rounded-lg hover:bg-red-50">
                    Kijelentkezés
                  </button>
                </div>
              )}
            </div>
          </div>
        </div>
      )}
    </nav>
  );
};
