import { useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { getLeaderboard } from '../../api/gamification'
import type { LeaderboardEntry } from '../../types/gamification'

type Category = 'profit' | 'wagered' | 'wins' | 'streak' | 'xp'

const CATEGORY_LABELS: Record<Category, string> = {
  profit: 'Top Earners',
  wagered: 'High Rollers',
  wins: 'Most Wins',
  streak: 'Hot Streaks',
  xp: 'XP Leaders',
}

const TIER_COLORS: Record<string, string> = {
  'Bronze I': 'text-amber-700',
  'Bronze II': 'text-amber-700',
  'Bronze III': 'text-amber-700',
  'Silver I': 'text-gray-500',
  'Silver II': 'text-gray-500',
  'Silver III': 'text-gray-500',
  'Gold I': 'text-yellow-600',
  'Gold II': 'text-yellow-600',
  'Gold III': 'text-yellow-600',
  'Platinum': 'text-cyan-600',
  'Diamond': 'text-purple-600',
}

function getRankIcon(rank: number): string {
  if (rank === 1) return '🥇'
  if (rank === 2) return '🥈'
  if (rank === 3) return '🥉'
  return `#${rank}`
}

function formatValue(value: number, category: Category): string {
  if (category === 'profit' || category === 'wagered') {
    return `$${value.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`
  }
  if (category === 'xp') {
    return `${value.toLocaleString()} XP`
  }
  return value.toString()
}

export default function Leaderboard() {
  const [category, setCategory] = useState<Category>('profit')

  const { data: entries = [], isLoading } = useQuery({
    queryKey: ['leaderboard', category],
    queryFn: () => getLeaderboard(category, 10),
    refetchInterval: 30000,
    retry: 1,
  })

  return (
    <div className="bg-white rounded-xl shadow-sm p-6">
      <h3 className="text-lg font-bold text-gray-900 mb-4 flex items-center gap-2">
        <span className="text-2xl">🏆</span> Leaderboard
      </h3>

      {/* Category Tabs */}
      <div className="flex gap-1 mb-4 overflow-x-auto pb-2">
        {(Object.keys(CATEGORY_LABELS) as Category[]).map((cat) => (
          <button
            key={cat}
            onClick={() => setCategory(cat)}
            className={`px-3 py-1.5 rounded-lg text-xs font-medium whitespace-nowrap transition-colors ${
              category === cat
                ? 'bg-primary text-white'
                : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
            }`}
          >
            {CATEGORY_LABELS[cat]}
          </button>
        ))}
      </div>

      {/* Leaderboard List */}
      {isLoading ? (
        <div className="space-y-2">
          {[...Array(5)].map((_, i) => (
            <div key={i} className="h-12 bg-gray-100 rounded-lg animate-pulse" />
          ))}
        </div>
      ) : entries.length === 0 ? (
        <p className="text-gray-500 text-center py-4">No entries yet</p>
      ) : (
        <div className="space-y-2">
          {entries.map((entry: LeaderboardEntry) => (
            <div
              key={entry.user_id}
              className={`flex items-center gap-3 p-3 rounded-lg ${
                entry.rank <= 3 ? 'bg-primary/5 border border-primary/20' : 'bg-gray-50'
              }`}
            >
              <span className={`w-8 text-center font-bold ${entry.rank <= 3 ? 'text-lg' : 'text-sm text-gray-500'}`}>
                {getRankIcon(entry.rank)}
              </span>

              <div className="w-10 h-10 rounded-full bg-gray-200 flex items-center justify-center overflow-hidden">
                {entry.avatar_url ? (
                  <img src={entry.avatar_url} alt="" className="w-full h-full object-cover" />
                ) : (
                  <span className="text-sm font-medium text-gray-600">{entry.username[0].toUpperCase()}</span>
                )}
              </div>

              <div className="flex-1 min-w-0">
                <p className="text-gray-900 font-medium text-sm truncate">
                  {entry.display_name || entry.username}
                </p>
                <p className={`text-xs ${TIER_COLORS[entry.tier_name] || 'text-gray-500'}`}>
                  {entry.tier_name}
                </p>
              </div>

              <span className="text-green-600 font-bold text-sm">
                {formatValue(entry.value, category)}
              </span>
            </div>
          ))}
        </div>
      )}
    </div>
  )
}
