import { useState, useEffect } from 'react'
import { useNavigate, useLocation } from 'react-router-dom'
import { useAuth } from '../hooks/useAuth'
import { useGameWebSocket } from '../hooks/useGameWebSocket'
import api from '../services/api'
import { useTranslation } from 'react-i18next'
import LanguageSelector from './LanguageSelector'
import './Game.css'

import { GameTooltip } from './common/GameTooltip'

// Import the new specific header styles
import './GameHeader.css'

interface GameHeaderProps {
  className?: string
}

export default function GameHeader({ className = '' }: GameHeaderProps) {
  const navigate = useNavigate()
  const location = useLocation()
  const { currentCharacter, logout } = useAuth()
  const { t } = useTranslation()
  const [playerCount, setPlayerCount] = useState<number>(0)

  // Fetch initial player count
  useEffect(() => {
    const fetchPlayerCount = async () => {
      try {
        const response = await api.get('/api/statistics/online-players')
        if (response.data && typeof response.data.count === 'number') {
          setPlayerCount(response.data.count)
        }
      } catch (error) {
        console.error('Failed to fetch player count:', error)
      }
    }

    fetchPlayerCount()
  }, [])

  // Connect to WebSocket for player count updates
  // We use a separate connection here to ensure the header always has live data
  // regardless of which page is active (Game, Leaderboards, Profile)
  const token = localStorage.getItem('token')

  useGameWebSocket({
    token,
    enabled: !!token,
    onMessage: (message) => {
      if (message.type === 'player_count_update' && message.data?.count !== undefined) {
        //console.log('🔢 GameHeader received count update:', message.data.count)
        setPlayerCount(message.data.count)
      }
    }
  })

  const isActive = (path: string) => {
    return location.pathname === path || location.pathname.startsWith(path)
  }

  const isOnOwnProfile = location.pathname === `/profile/${currentCharacter?.id}`

  return (
    <header className={`game-header ${className}`}>
      <div className="header-left">
        <div className="header-title-container">
          <h1>Echoes of the Ash</h1>
          <span className="header-version">v0.9</span>
        </div>
      </div>

      <nav className="nav-links">
        <button
          onClick={() => navigate('/game')}
          className={`nav-link ${isActive('/game') ? 'active' : ''}`}
        >
          <span style={{ fontSize: '1.1em' }}>🎮</span> {t('common.game')}
        </button>
        <button
          onClick={() => navigate('/leaderboards')}
          className={`nav-link ${isActive('/leaderboards') ? 'active' : ''}`}
        >
          <span style={{ fontSize: '1.1em' }}>🏆</span> {t('common.leaderboards')}
        </button>
      </nav>

      <div className="user-info">
        <GameTooltip content={t('game.onlineCount', { count: playerCount })}>
          <div className="player-count-badge">
            <span className="status-dot"></span>
            <span className="count-text">{playerCount}</span>
          </div>
        </GameTooltip>

        <LanguageSelector />

        <button
          onClick={() => navigate(`/profile/${currentCharacter?.id}`)}
          className={`username-link ${isOnOwnProfile ? 'active' : ''}`}
        >
          {currentCharacter?.name}
        </button>

        <div className="header-sep"></div>

        <GameTooltip content={t('common.account')}>
          <button
            onClick={() => navigate('/account')}
            className="header-icon-btn"
            aria-label={t('common.account')}
          >
            ⚙️
          </button>
        </GameTooltip>

        <GameTooltip content={t('auth.logout')}>
          <button onClick={logout} className="header-icon-btn" aria-label={t('auth.logout')}>
            🚪
          </button>
        </GameTooltip>
      </div>
    </header>
  )
}
