import { useQuery } from '@tanstack/react-query'
import { getMyStats, getTierInfo } from '../../api/gamification'
import type { TierInfo } from '../../types/gamification'

const TIER_ICONS: Record<string, string> = {
  'Bronze I': '🥉',
  'Bronze II': '🥉',
  'Bronze III': '🥉',
  'Silver I': '🥈',
  'Silver II': '🥈',
  'Silver III': '🥈',
  'Gold I': '🥇',
  'Gold II': '🥇',
  'Gold III': '🥇',
  'Platinum': '💎',
  'Diamond': '👑',
}

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

interface TierProgressProps {
  compact?: boolean
}

export default function TierProgress({ compact = false }: TierProgressProps) {
  const { data: stats, isLoading: loadingStats } = useQuery({
    queryKey: ['my-stats'],
    queryFn: getMyStats,
    retry: 1,
  })

  const { data: tiers = [], isLoading: loadingTiers } = useQuery({
    queryKey: ['tier-info'],
    queryFn: getTierInfo,
    retry: 1,
  })

  const isLoading = loadingStats || loadingTiers

  if (isLoading) {
    return (
      <div className="bg-white rounded-xl shadow-sm p-6">
        <div className="h-32 bg-gray-100 rounded-lg animate-pulse" />
      </div>
    )
  }

  if (!stats) {
    return null
  }

  const tierColors = TIER_COLORS[stats.tier_name] || TIER_COLORS['Bronze I']
  const tierIcon = TIER_ICONS[stats.tier_name] || '🏅'

  if (compact) {
    return (
      <div className="bg-white rounded-xl shadow-sm p-4">
        <div className="flex items-center gap-3">
          <div className="text-3xl">{tierIcon}</div>
          <div className="flex-1">
            <div className="flex items-center justify-between mb-1">
              <span className={`font-bold ${tierColors.text}`}>{stats.tier_name}</span>
              <span className="text-xs text-gray-500">{stats.xp.toLocaleString()} XP</span>
            </div>
            <div className="h-2 bg-gray-100 rounded-full overflow-hidden">
              <div
                className={`h-full ${tierColors.bg} transition-all duration-500`}
                style={{ width: `${stats.tier_progress_percent}%` }}
              />
            </div>
            <p className="text-xs text-gray-500 mt-1">
              {stats.tier < 10
                ? `${stats.xp_to_next_tier.toLocaleString()} XP to next tier`
                : 'Max tier reached!'}
            </p>
          </div>
        </div>
      </div>
    )
  }

  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> Your Tier
      </h3>

      {/* Current Tier Display */}
      <div className={`border-2 ${tierColors.border} rounded-xl p-4 mb-4 bg-gradient-to-br from-gray-50 to-transparent`}>
        <div className="flex items-center gap-4">
          <div className="text-5xl">{tierIcon}</div>
          <div className="flex-1">
            <p className={`text-2xl font-bold ${tierColors.text}`}>{stats.tier_name}</p>
            <p className="text-gray-500 text-sm">Tier {stats.tier} of 10</p>
          </div>
          <div className="text-right">
            <p className="text-green-600 font-bold text-lg">{stats.house_fee}%</p>
            <p className="text-xs text-gray-500">House Fee</p>
          </div>
        </div>

        {/* XP Progress */}
        <div className="mt-4">
          <div className="flex justify-between text-sm mb-1">
            <span className="text-gray-600">{stats.xp.toLocaleString()} XP</span>
            {stats.tier < 10 && (
              <span className="text-gray-600">
                {(stats.xp + stats.xp_to_next_tier).toLocaleString()} XP
              </span>
            )}
          </div>
          <div className="h-3 bg-gray-100 rounded-full overflow-hidden">
            <div
              className={`h-full ${tierColors.bg} transition-all duration-500`}
              style={{ width: `${stats.tier_progress_percent}%` }}
            />
          </div>
          <p className="text-center text-sm text-gray-500 mt-2">
            {stats.tier < 10
              ? `${stats.xp_to_next_tier.toLocaleString()} XP to next tier`
              : '🎉 Max tier reached!'}
          </p>
        </div>
      </div>

      {/* Stats Summary */}
      <div className="grid grid-cols-2 gap-3 mb-4">
        <div className="bg-gray-50 rounded-lg p-3 text-center border">
          <p className={`text-lg font-bold ${stats.net_profit >= 0 ? 'text-green-600' : 'text-red-600'}`}>
            ${stats.net_profit >= 0 ? '+' : ''}{stats.net_profit.toLocaleString()}
          </p>
          <p className="text-xs text-gray-500">Net Profit</p>
        </div>
        <div className="bg-gray-50 rounded-lg p-3 text-center border">
          <p className="text-lg font-bold text-gray-900">${stats.total_wagered.toLocaleString()}</p>
          <p className="text-xs text-gray-500">Total Wagered</p>
        </div>
      </div>

      {/* Tier Roadmap */}
      <details className="group">
        <summary className="text-sm text-gray-500 cursor-pointer hover:text-gray-700 flex items-center gap-1">
          <span className="group-open:rotate-90 transition-transform">▶</span>
          View all tiers & benefits
        </summary>
        <div className="mt-3 space-y-1 max-h-48 overflow-y-auto">
          {tiers.map((tier: TierInfo) => {
            const isCurrentTier = tier.tier === stats.tier
            const isUnlocked = tier.tier <= stats.tier
            const colors = TIER_COLORS[tier.name] || TIER_COLORS['Bronze I']

            return (
              <div
                key={tier.tier}
                className={`flex items-center gap-2 p-2 rounded-lg text-sm ${
                  isCurrentTier
                    ? `${colors.border} border bg-gray-50`
                    : isUnlocked
                    ? 'bg-gray-50'
                    : 'bg-white opacity-60'
                }`}
              >
                <span className="text-lg">{TIER_ICONS[tier.name] || '🏅'}</span>
                <div className="flex-1">
                  <span className={isUnlocked ? colors.text : 'text-gray-400'}>
                    {tier.name}
                  </span>
                  <span className="text-gray-400 text-xs ml-2">
                    {tier.min_xp.toLocaleString()} XP
                  </span>
                </div>
                <span className={`font-medium ${isUnlocked ? 'text-green-600' : 'text-gray-400'}`}>
                  {tier.house_fee}%
                </span>
                {isCurrentTier && (
                  <span className="text-xs bg-primary text-white px-1.5 py-0.5 rounded">
                    YOU
                  </span>
                )}
              </div>
            )
          })}
        </div>
      </details>
    </div>
  )
}
