import { useState, useRef, useEffect } from 'react'
import { Link } from 'react-router-dom'
import { useAuthStore } from '@/store'
import { Wallet, LogOut, User, ChevronDown, Trophy, Medal, Gift, Activity, LayoutDashboard } from 'lucide-react'
import { useWeb3Wallet } from '@/blockchain/hooks/useWeb3Wallet'
import { Button } from '@/components/common/Button'

const REWARDS_DROPDOWN = [
  { path: '/rewards', label: 'Overview', icon: LayoutDashboard },
  { path: '/rewards/leaderboard', label: 'Leaderboard', icon: Trophy },
  { path: '/rewards/achievements', label: 'Achievements', icon: Medal },
  { path: '/rewards/loot-boxes', label: 'Loot Boxes', icon: Gift },
  { path: '/rewards/activity', label: 'Activity', icon: Activity },
]

function RewardsDropdown() {
  const [isOpen, setIsOpen] = useState(false)
  const dropdownRef = useRef<HTMLDivElement>(null)

  useEffect(() => {
    function 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 (
    <div className="relative" ref={dropdownRef}>
      <button
        onClick={() => setIsOpen(!isOpen)}
        className="flex items-center gap-1 text-gray-700 hover:text-primary transition-colors"
      >
        Rewards
        <ChevronDown size={16} className={`transition-transform ${isOpen ? 'rotate-180' : ''}`} />
      </button>

      {isOpen && (
        <div className="absolute top-full left-0 mt-2 w-48 bg-white rounded-lg shadow-lg border py-1 z-50">
          {REWARDS_DROPDOWN.map((item) => {
            const Icon = item.icon
            return (
              <Link
                key={item.path}
                to={item.path}
                onClick={() => setIsOpen(false)}
                className="flex items-center gap-2 px-4 py-2 text-gray-700 hover:bg-gray-50 hover:text-primary transition-colors"
              >
                <Icon size={16} />
                {item.label}
              </Link>
            )
          })}
        </div>
      )}
    </div>
  )
}

export const Header = () => {
  const { user, logout } = useAuthStore()
  const { walletAddress, isConnected, connectWallet, disconnectWallet } = useWeb3Wallet()

  return (
    <header className="bg-white shadow-sm border-b">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div className="flex justify-between items-center h-16">
          <Link to="/" className="flex items-center">
            <h1 className="text-2xl font-bold text-primary">H2H</h1>
          </Link>

          {user ? (
            // Logged in navigation
            <nav className="flex items-center gap-6">
              <Link to="/sports" className="text-gray-700 hover:text-primary transition-colors">
                Sports
              </Link>
              <Link to="/live" className="text-gray-700 hover:text-primary transition-colors">
                Live
              </Link>
              <Link to="/new-bets" className="text-gray-700 hover:text-primary transition-colors">
                New Bets
              </Link>
              <Link to="/watchlist" className="text-gray-700 hover:text-primary transition-colors">
                Watchlist
              </Link>
              <RewardsDropdown />

              <div className="flex items-center gap-4 pl-4 border-l">
                {user.is_admin && (
                  <Link to="/admin" className="text-gray-700 hover:text-primary transition-colors">
                    Admin
                  </Link>
                )}
                <Link to="/my-bets" className="text-gray-700 hover:text-primary transition-colors">
                  My Bets
                </Link>
                <Link to="/wallet" className="flex items-center gap-2 text-gray-700 hover:text-primary transition-colors">
                  <Wallet size={18} />
                  Wallet
                </Link>
              </div>

              {/* Web3 Wallet Connection */}
              {isConnected ? (
                <button
                  onClick={disconnectWallet}
                  className="flex items-center gap-2 px-3 py-1.5 bg-green-100 text-green-800 rounded-lg hover:bg-green-200 transition-colors text-sm font-medium"
                >
                  <span>⛓️</span>
                  <span>{walletAddress?.substring(0, 6)}...{walletAddress?.substring(38)}</span>
                </button>
              ) : (
                <button
                  onClick={connectWallet}
                  className="flex items-center gap-2 px-3 py-1.5 bg-blue-100 text-blue-800 rounded-lg hover:bg-blue-200 transition-colors text-sm font-medium"
                >
                  <span>⛓️</span>
                  <span>Connect Wallet</span>
                </button>
              )}

              <div className="flex items-center gap-4 pl-4 border-l">
                <Link to="/profile" className="flex items-center gap-2 text-gray-700 hover:text-primary transition-colors">
                  <User size={18} />
                  {user.display_name || user.username}
                </Link>
                <button
                  onClick={logout}
                  className="flex items-center gap-2 text-gray-700 hover:text-error transition-colors"
                >
                  <LogOut size={18} />
                  Logout
                </button>
              </div>
            </nav>
          ) : (
            // Non-logged in navigation
            <nav className="flex items-center gap-6">
              <Link to="/sports" className="text-gray-700 hover:text-primary transition-colors">
                Sports
              </Link>
              <Link to="/live" className="text-gray-700 hover:text-primary transition-colors">
                Live
              </Link>
              <Link to="/new-bets" className="text-gray-700 hover:text-primary transition-colors">
                New Bets
              </Link>
              <Link to="/watchlist" className="text-gray-700 hover:text-primary transition-colors">
                Watchlist
              </Link>
              <RewardsDropdown />
              <Link to="/how-it-works" className="text-gray-700 hover:text-primary transition-colors">
                How It Works
              </Link>
              <div className="flex items-center gap-3 pl-4 border-l">
                <Link to="/login">
                  <Button variant="secondary" size="sm">
                    Log In
                  </Button>
                </Link>
                <Link to="/register">
                  <Button size="sm">
                    Sign Up
                  </Button>
                </Link>
              </div>
            </nav>
          )}
        </div>
      </div>
    </header>
  )
}
