import { useState, useRef, useEffect } from 'react'
import { Link } from 'react-router-dom'
import { useAuthStore } from '@/store'
import {
  Wallet,
  LogOut,
  User,
  ChevronDown,
  Gift,
  Crown,
  Users,
  Rocket,
  Share2,
  Settings,
  Receipt
} from 'lucide-react'
import { useWeb3Wallet } from '@/blockchain/hooks/useWeb3Wallet'
import { Button } from '@/components/common/Button'

// More dropdown menu items
const MORE_DROPDOWN = [
  {
    path: '/vip',
    label: 'VIP & Institutional',
    description: 'Your trusted digital betting platform for VIPs and institutions',
    icon: Crown
  },
  {
    path: '/affiliate',
    label: 'Affiliate',
    description: 'Earn up to 50% commission per bet from referrals',
    icon: Users
  },
  {
    path: '/referral',
    label: 'Referral',
    description: 'Invite friends to earn either a commission rebate or a one-time reward',
    icon: Share2
  },
  {
    path: '/launchpool',
    label: 'Launchpool',
    description: 'Discover and gain access to new bets',
    icon: Rocket
  },
]

// Reusable dropdown hook
function useDropdown() {
  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 { isOpen, setIsOpen, dropdownRef }
}

function MoreDropdown() {
  const { isOpen, setIsOpen, dropdownRef } = useDropdown()

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

      {isOpen && (
        <div className="absolute top-full left-0 mt-2 w-72 bg-white rounded-lg shadow-lg border py-2 z-50">
          {MORE_DROPDOWN.map((item) => {
            const Icon = item.icon
            return (
              <Link
                key={item.path}
                to={item.path}
                onClick={() => setIsOpen(false)}
                className="flex items-start gap-3 px-4 py-3 hover:bg-gray-50 transition-colors"
              >
                <Icon size={20} className="text-primary mt-0.5 flex-shrink-0" />
                <div>
                  <p className="font-medium text-gray-900">{item.label}</p>
                  <p className="text-xs text-gray-500 mt-0.5">{item.description}</p>
                </div>
              </Link>
            )
          })}
        </div>
      )}
    </div>
  )
}

function ProfileDropdown() {
  const { user, logout } = useAuthStore()
  const { walletAddress, isConnected, connectWallet, disconnectWallet } = useWeb3Wallet()
  const { isOpen, setIsOpen, dropdownRef } = useDropdown()

  if (!user) return null

  return (
    <div className="relative" ref={dropdownRef}>
      <button
        onClick={() => setIsOpen(!isOpen)}
        className="flex items-center gap-2 text-gray-700 hover:text-primary transition-colors"
      >
        <User size={18} />
        <span className="font-medium">{user.display_name || user.username}</span>
        <ChevronDown size={16} className={`transition-transform ${isOpen ? 'rotate-180' : ''}`} />
      </button>

      {isOpen && (
        <div className="absolute top-full right-0 mt-2 w-56 bg-white rounded-lg shadow-lg border py-2 z-50">
          {/* User info header */}
          <div className="px-4 py-2 border-b">
            <p className="font-medium text-gray-900">{user.display_name || user.username}</p>
            <p className="text-sm text-gray-500">{user.email}</p>
          </div>

          {/* Menu items */}
          <div className="py-1">
            <Link
              to="/profile"
              onClick={() => setIsOpen(false)}
              className="flex items-center gap-3 px-4 py-2 text-gray-700 hover:bg-gray-50 hover:text-primary transition-colors"
            >
              <Settings size={16} />
              Profile Settings
            </Link>
            <Link
              to="/my-bets"
              onClick={() => setIsOpen(false)}
              className="flex items-center gap-3 px-4 py-2 text-gray-700 hover:bg-gray-50 hover:text-primary transition-colors"
            >
              <Receipt size={16} />
              My Bets
            </Link>
            <Link
              to="/wallet"
              onClick={() => setIsOpen(false)}
              className="flex items-center gap-3 px-4 py-2 text-gray-700 hover:bg-gray-50 hover:text-primary transition-colors"
            >
              <Wallet size={16} />
              Wallet
            </Link>
          </div>

          {/* Web3 Wallet section */}
          <div className="border-t py-1">
            {isConnected ? (
              <button
                onClick={() => {
                  disconnectWallet()
                  setIsOpen(false)
                }}
                className="w-full flex items-center gap-3 px-4 py-2 text-gray-700 hover:bg-gray-50 transition-colors"
              >
                <span className="text-green-600">&#x26D3;</span>
                <div className="text-left">
                  <p className="text-sm font-medium text-green-700">Wallet Connected</p>
                  <p className="text-xs text-gray-500">{walletAddress?.substring(0, 6)}...{walletAddress?.substring(38)}</p>
                </div>
              </button>
            ) : (
              <button
                onClick={() => {
                  connectWallet()
                  setIsOpen(false)
                }}
                className="w-full flex items-center gap-3 px-4 py-2 text-gray-700 hover:bg-gray-50 transition-colors"
              >
                <span>&#x26D3;</span>
                <span className="text-sm">Connect Web3 Wallet</span>
              </button>
            )}
          </div>

          {/* Logout */}
          <div className="border-t py-1">
            <button
              onClick={() => {
                logout()
                setIsOpen(false)
              }}
              className="w-full flex items-center gap-3 px-4 py-2 text-gray-700 hover:bg-red-50 hover:text-red-600 transition-colors"
            >
              <LogOut size={16} />
              Logout
            </button>
          </div>
        </div>
      )}
    </div>
  )
}

export const Header = () => {
  const { user } = useAuthStore()

  return (
    <header className="bg-white shadow-sm border-b">
      <div className="px-4 sm:px-6 lg:px-8">
        <div className="flex items-center h-16">
          {/* Logo */}
          <Link to="/" className="flex items-center">
            <h1 className="text-2xl font-bold text-primary">H2H</h1>
          </Link>

          {/* Left-justified navigation links */}
          <nav className="flex items-center gap-6 ml-8">
            <Link to="/" className="text-gray-700 hover:text-primary transition-colors">
              Events
            </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="/how-it-works" className="text-gray-700 hover:text-primary transition-colors">
              How It Works
            </Link>
            {/* Watchlist only shows for logged-in users */}
            {user && (
              <Link to="/watchlist" className="text-gray-700 hover:text-primary transition-colors">
                Watchlist
              </Link>
            )}
            <MoreDropdown />
            {/* Rewards Center button - styled like CoinEx */}
            <Link
              to="/rewards"
              className="flex items-center gap-1.5 px-3 py-1.5 border border-orange-400 text-orange-500 rounded-full hover:bg-orange-50 transition-colors text-sm font-medium"
            >
              <Gift size={16} />
              Reward Center
            </Link>
          </nav>

          {/* Right side - Auth buttons or Profile */}
          <div className="ml-auto flex items-center gap-4">
            {user ? (
              <>
                {/* Admin link if admin */}
                {user.is_admin && (
                  <Link to="/admin" className="text-gray-700 hover:text-primary transition-colors">
                    Admin
                  </Link>
                )}
                {/* Profile dropdown */}
                <ProfileDropdown />
              </>
            ) : (
              <div className="flex items-center gap-3">
                <Link to="/login">
                  <Button variant="secondary" size="sm">
                    Log In
                  </Button>
                </Link>
                <Link to="/register">
                  <Button size="sm">
                    Sign Up
                  </Button>
                </Link>
              </div>
            )}
          </div>
        </div>
      </div>
    </header>
  )
}
