import { useEffect, useState } from 'react'
import { useParams, useNavigate } from 'react-router-dom'
import api from '../services/api'
import './Profile.css'
import './Game.css'

interface PlayerStats {
  id: number
  player_id: number
  distance_walked: number
  enemies_killed: number
  damage_dealt: number
  damage_taken: number
  hp_restored: number
  stamina_used: number
  stamina_restored: number
  items_collected: number
  items_dropped: number
  items_used: number
  deaths: number
  successful_flees: number
  failed_flees: number
  combats_initiated: number
  total_playtime: number
  last_activity: number
  created_at: number
}

interface PlayerInfo {
  id: number
  username: string
  name: string
  level: number
}

interface ProfileData {
  player: PlayerInfo
  statistics: PlayerStats
}

function Profile() {
  const { playerId } = useParams<{ playerId: string }>()
  const navigate = useNavigate()
  const [profile, setProfile] = useState<ProfileData | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [mobileHeaderOpen, setMobileHeaderOpen] = useState(false)

  useEffect(() => {
    fetchProfile()
  }, [playerId])

  const fetchProfile = async () => {
    try {
      setLoading(true)
      const response = await api.get(`/api/statistics/${playerId}`)
      setProfile(response.data)
      setError(null)
    } catch (err: any) {
      setError(err.response?.data?.detail || 'Failed to load profile')
    } finally {
      setLoading(false)
    }
  }

  const formatPlaytime = (seconds: number) => {
    const hours = Math.floor(seconds / 3600)
    const minutes = Math.floor((seconds % 3600) / 60)
    if (hours > 0) {
      return `${hours}h ${minutes}m`
    }
    return `${minutes}m`
  }

  const formatDate = (timestamp: number) => {
    if (!timestamp) return 'Never'
    return new Date(timestamp * 1000).toLocaleDateString()
  }

  if (loading) {
    return (
      <div className="profile-page">
        <div className="profile-loading">Loading profile...</div>
      </div>
    )
  }

  if (error || !profile) {
    return (
      <div className="profile-page">
        <div className="profile-error">
          <h2>Error</h2>
          <p>{error || 'Profile not found'}</p>
          <button onClick={() => navigate('/leaderboards')}>Back to Leaderboards</button>
        </div>
      </div>
    )
  }

  const stats = profile.statistics
  const player = profile.player

  return (
    <div className="game-container">
      {/* Game Header is now in GameLayout */}

      {/* Mobile Header Toggle */}
      <button
        className="mobile-header-toggle"
        onClick={() => setMobileHeaderOpen(!mobileHeaderOpen)}
      >
        {mobileHeaderOpen ? '✕' : '☰'}
      </button>

      <main className="game-main">
        <div className="profile-container">
          <div className="profile-info-card">
            <div className="profile-avatar">
              <span className="avatar-icon">👤</span>
            </div>
            <h1 className="profile-name">{player.name}</h1>
            <p className="profile-username">@{player.username}</p>
            <div className="profile-level">Level {player.level}</div>
            <div className="profile-meta">
              <div className="meta-item">
                <span className="meta-label">Member since</span>
                <span className="meta-value">{formatDate(stats.created_at)}</span>
              </div>
              <div className="meta-item">
                <span className="meta-label">Last seen</span>
                <span className="meta-value">{formatDate(stats.last_activity)}</span>
              </div>
            </div>
          </div>

          <div className="profile-stats-grid">
            {/* Combat Stats */}
            <div className="stats-section">
              <h2 className="section-title">⚔️ Combat</h2>
              <div className="stat-row">
                <span className="stat-label">Enemies Killed</span>
                <span className="stat-value">{stats.enemies_killed.toLocaleString()}</span>
              </div>
              <div className="stat-row">
                <span className="stat-label">Combats Initiated</span>
                <span className="stat-value">{stats.combats_initiated.toLocaleString()}</span>
              </div>
              <div className="stat-row">
                <span className="stat-label">Damage Dealt</span>
                <span className="stat-value highlight-red">{stats.damage_dealt.toLocaleString()}</span>
              </div>
              <div className="stat-row">
                <span className="stat-label">Damage Taken</span>
                <span className="stat-value">{stats.damage_taken.toLocaleString()}</span>
              </div>
              <div className="stat-row">
                <span className="stat-label">Deaths</span>
                <span className="stat-value">{stats.deaths.toLocaleString()}</span>
              </div>
              <div className="stat-row">
                <span className="stat-label">Successful Flees</span>
                <span className="stat-value highlight-green">{stats.successful_flees.toLocaleString()}</span>
              </div>
              <div className="stat-row">
                <span className="stat-label">Failed Flees</span>
                <span className="stat-value">{stats.failed_flees.toLocaleString()}</span>
              </div>
            </div>

            {/* Exploration Stats */}
            <div className="stats-section">
              <h2 className="section-title">🗺️ Exploration</h2>
              <div className="stat-row">
                <span className="stat-label">Distance Walked</span>
                <span className="stat-value highlight-blue">{stats.distance_walked.toLocaleString()}</span>
              </div>
              <div className="stat-row">
                <span className="stat-label">Playtime</span>
                <span className="stat-value">{formatPlaytime(stats.total_playtime)}</span>
              </div>
            </div>

            {/* Items Stats */}
            <div className="stats-section">
              <h2 className="section-title">📦 Items</h2>
              <div className="stat-row">
                <span className="stat-label">Items Collected</span>
                <span className="stat-value">{stats.items_collected.toLocaleString()}</span>
              </div>
              <div className="stat-row">
                <span className="stat-label">Items Dropped</span>
                <span className="stat-value">{stats.items_dropped.toLocaleString()}</span>
              </div>
              <div className="stat-row">
                <span className="stat-label">Items Used</span>
                <span className="stat-value">{stats.items_used.toLocaleString()}</span>
              </div>
            </div>

            {/* Recovery Stats */}
            <div className="stats-section">
              <h2 className="section-title">❤️ Recovery</h2>
              <div className="stat-row">
                <span className="stat-label">HP Restored</span>
                <span className="stat-value highlight-hp">{stats.hp_restored.toLocaleString()}</span>
              </div>
              <div className="stat-row">
                <span className="stat-label">Stamina Used</span>
                <span className="stat-value">{stats.stamina_used.toLocaleString()}</span>
              </div>
              <div className="stat-row">
                <span className="stat-label">Stamina Restored</span>
                <span className="stat-value highlight-stamina">{stats.stamina_restored.toLocaleString()}</span>
              </div>
            </div>
          </div>
        </div>
      </main>
    </div>
  )
}

export default Profile
