import { useState, useEffect } from 'react';
import { Link, useLocation, useNavigate } from 'react-router-dom';
import { motion, AnimatePresence } from 'framer-motion';
import {
  LayoutDashboard, Crosshair, History, Trophy,
  User, Settings, LogOut, ChevronDown, Shield, Menu, X
} from 'lucide-react';
import { cn } from '@/lib/cn';
import { useAuthStore } from '@/stores/authStore';
import { Avatar } from '@/components/ui/Avatar';
import { authAPI } from '@/api/client';

const navLinks = [
  { path: '/dashboard', label: 'Dashboard', icon: LayoutDashboard },
  { path: '/queue', label: 'Play', icon: Crosshair },
  { path: '/history', label: 'Matches', icon: History },
  { path: '/leaderboard', label: 'Ranks', icon: Trophy },
];

export function Navbar() {
  const location = useLocation();
  const navigate = useNavigate();
  const { user, isAuthenticated } = useAuthStore();
  const logout = useAuthStore((s) => s.logout);
  const [dropdownOpen, setDropdownOpen] = useState(false);
  const [mobileOpen, setMobileOpen] = useState(false);
  const [scrolled, setScrolled] = useState(false);

  const isAdmin = user?.role === 'admin' || user?.role === 'owner' || user?.role === 'moderator';

  useEffect(() => {
    const handleScroll = () => setScrolled(window.scrollY > 10);
    window.addEventListener('scroll', handleScroll, { passive: true });
    return () => window.removeEventListener('scroll', handleScroll);
  }, []);

  useEffect(() => { setMobileOpen(false); }, [location.pathname]);

  const handleLogout = () => {
    const refreshToken = useAuthStore.getState().refreshToken;
    logout();
    navigate('/');
    if (refreshToken) {
      authAPI.logout(refreshToken).catch(() => {});
    }
  };

  return (
    <nav
      className={cn(
        'sticky top-0 z-50 transition-all duration-500',
        scrolled
          ? 'bg-[#06060b]/85 backdrop-blur-2xl border-b border-[#1e1e30]/80 shadow-[0_4px_30px_rgba(0,0,0,0.4)]'
          : 'bg-transparent border-b border-transparent'
      )}
    >
      <div
        className={cn(
          'absolute bottom-0 left-0 right-0 h-px transition-opacity duration-500',
          scrolled ? 'opacity-100' : 'opacity-0'
        )}
        style={{
          background: 'linear-gradient(90deg, transparent 10%, #ff6b2c40 50%, transparent 90%)',
        }}
      />

      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div className="flex items-center justify-between h-16">
          <Link to={isAuthenticated ? '/dashboard' : '/'} className="flex items-center group">
            <span className="text-xl font-black tracking-tight text-[#f0f0f5] font-display">
              tapper<span className="text-[#ff6b2c] group-hover:text-[#ff8a50] transition-colors duration-200">.</span>
            </span>
          </Link>

          {isAuthenticated && (
            <div className="hidden md:flex items-center gap-0.5 bg-[#0d0d14]/60 border border-[#1e1e30]/60 rounded-xl p-1">
              {navLinks.map((link) => {
                const isActive = location.pathname === link.path;
                return (
                  <Link
                    key={link.path}
                    to={link.path}
                    className={cn(
                      'relative px-4 py-2 text-[13px] font-semibold rounded-lg transition-all duration-200',
                      isActive
                        ? 'text-white'
                        : 'text-[#5a5a72] hover:text-[#a0a0b8]'
                    )}
                  >
                    {isActive && (
                      <motion.div
                        layoutId="nav-pill"
                        className="absolute inset-0 bg-gradient-to-r from-[#ff6b2c]/15 to-[#ff6b2c]/5 border border-[#ff6b2c]/20 rounded-lg"
                        transition={{ type: 'spring', stiffness: 400, damping: 30 }}
                      />
                    )}
                    <span className="relative z-10 flex items-center gap-2">
                      <link.icon className="w-3.5 h-3.5" />
                      {link.label}
                    </span>
                  </Link>
                );
              })}
              {isAdmin && (
                <Link
                  to="/admin"
                  className={cn(
                    'relative px-4 py-2 text-[13px] font-semibold rounded-lg transition-all duration-200 flex items-center gap-2',
                    location.pathname.startsWith('/admin')
                      ? 'text-[#ff6b2c]'
                      : 'text-[#5a5a72] hover:text-[#a0a0b8]'
                  )}
                >
                  <Shield className="w-3.5 h-3.5" />
                  Admin
                </Link>
              )}
            </div>
          )}

          <div className="flex items-center gap-3">
            {isAuthenticated && user ? (
              <div className="relative">
                <button
                  onClick={() => setDropdownOpen(!dropdownOpen)}
                  className={cn(
                    'flex items-center gap-2.5 px-3 py-1.5 rounded-xl transition-all duration-200',
                    'hover:bg-[#1a1a28]/60',
                    dropdownOpen && 'bg-[#1a1a28]/60'
                  )}
                >
                  <Avatar src={user.steam_avatar_url} username={user.username} size="sm" />
                  <span className="hidden sm:block text-sm font-semibold text-[#f0f0f5]">
                    {user.username}
                  </span>
                  <ChevronDown className={cn(
                    'w-3.5 h-3.5 text-[#5a5a72] transition-transform duration-200',
                    dropdownOpen && 'rotate-180'
                  )} />
                </button>

                <AnimatePresence>
                  {dropdownOpen && (
                    <>
                      <div className="fixed inset-0 z-40" onClick={() => setDropdownOpen(false)} />
                      <motion.div
                        initial={{ opacity: 0, y: -8, scale: 0.95 }}
                        animate={{ opacity: 1, y: 0, scale: 1 }}
                        exit={{ opacity: 0, y: -8, scale: 0.95 }}
                        transition={{ duration: 0.15, ease: 'easeOut' }}
                        className="absolute right-0 mt-2 w-56 bg-[#0d0d14] border border-[#1e1e30] rounded-xl shadow-[0_16px_48px_rgba(0,0,0,0.5)] z-50 overflow-hidden"
                      >
                        <div className="px-4 py-3 border-b border-[#1e1e30]">
                          <p className="text-sm font-semibold text-[#f0f0f5] truncate">{user.username}</p>
                          <p className="text-xs text-[#5a5a72] truncate mt-0.5">{user.email}</p>
                        </div>
                        <div className="py-1">
                          {[
                            { to: '/profile', icon: User, label: 'Profile' },
                            { to: '/settings', icon: Settings, label: 'Settings' },
                          ].map((item) => (
                            <Link
                              key={item.to}
                              to={item.to}
                              onClick={() => setDropdownOpen(false)}
                              className="flex items-center gap-3 px-4 py-2.5 text-sm text-[#a0a0b8] hover:text-[#f0f0f5] hover:bg-[#1a1a28]/60 transition-colors"
                            >
                              <item.icon className="w-4 h-4" />
                              {item.label}
                            </Link>
                          ))}
                        </div>
                        <div className="border-t border-[#1e1e30] py-1">
                          <button
                            onClick={() => {
                              setDropdownOpen(false);
                              handleLogout();
                            }}
                            className="w-full flex items-center gap-3 px-4 py-2.5 text-sm text-red-400 hover:bg-red-500/10 transition-colors"
                          >
                            <LogOut className="w-4 h-4" />
                            Log Out
                          </button>
                        </div>
                      </motion.div>
                    </>
                  )}
                </AnimatePresence>
              </div>
            ) : (
              <div className="flex items-center gap-2">
                <Link
                  to="/login"
                  className="px-4 py-2 text-sm font-semibold text-[#a0a0b8] hover:text-[#f0f0f5] transition-colors"
                >
                  Log In
                </Link>
                <Link
                  to="/register"
                  className="px-5 py-2.5 text-sm font-bold bg-gradient-to-r from-[#ff6b2c] to-[#e85d1c] text-white rounded-xl shadow-[0_4px_16px_rgba(255,107,44,0.3)] hover:shadow-[0_6px_24px_rgba(255,107,44,0.45)] hover:from-[#ff8a50] hover:to-[#ff6b2c] transition-all duration-300 btn-shine"
                >
                  Sign Up
                </Link>
              </div>
            )}

            {isAuthenticated && (
              <button
                className="md:hidden p-2 text-[#5a5a72] hover:text-[#f0f0f5] transition-colors"
                onClick={() => setMobileOpen(!mobileOpen)}
                aria-label="Toggle menu"
              >
                {mobileOpen ? <X className="w-5 h-5" /> : <Menu className="w-5 h-5" />}
              </button>
            )}
          </div>
        </div>
      </div>

      <AnimatePresence>
        {mobileOpen && isAuthenticated && (
          <motion.div
            initial={{ height: 0, opacity: 0 }}
            animate={{ height: 'auto', opacity: 1 }}
            exit={{ height: 0, opacity: 0 }}
            transition={{ duration: 0.25, ease: 'easeOut' }}
            className="md:hidden border-t border-[#1e1e30] overflow-hidden bg-[#06060b]/95 backdrop-blur-2xl"
          >
            <div className="px-4 py-3 space-y-1">
              {navLinks.map((link) => (
                <Link
                  key={link.path}
                  to={link.path}
                  onClick={() => setMobileOpen(false)}
                  className={cn(
                    'flex items-center gap-3 px-4 py-3 rounded-xl text-sm font-medium transition-all',
                    location.pathname === link.path
                      ? 'text-white bg-[#ff6b2c]/10 border border-[#ff6b2c]/20'
                      : 'text-[#5a5a72] hover:text-[#a0a0b8] hover:bg-[#1a1a28]/40'
                  )}
                >
                  <link.icon className="w-4 h-4" />
                  {link.label}
                </Link>
              ))}
            </div>
          </motion.div>
        )}
      </AnimatePresence>
    </nav>
  );
}
