"use client"

import { useState, useEffect } from 'react'
import { useTranslations } from 'next-intl'
import { Trophy, Crown, Medal, Award, DollarSign, User, Hash, Star, TrendingUp, Zap, Gem, Sparkles, Coins, Wallet, Banknote, Target, Shield, Flame, Users } from 'lucide-react'

interface LeaderboardEntry {
  accountId: number
  accountName: string
  totalMoney: number
  characterCount: number
  vip: number
  profilePhoto?: string | null
}

interface MoneyLeaderboardProps {
  limit?: number
  className?: string
}

const formatMoney = (amount: number) => {
  if (amount >= 1_000_000) {
    return `$${(amount / 1_000_000).toFixed(1)}M`
  }
  if (amount >= 1_000) {
    return `$${(amount / 1_000).toFixed(0)}K`
  }
  return `$${amount.toLocaleString()}`
}

const getRankIcon = (index: number) => {
  switch (index) {
    case 0:
      return <Crown className="w-5 h-5 text-yellow-400 drop-shadow-lg" />
    case 1:
      return <Medal className="w-5 h-5 text-gray-300 drop-shadow-lg" />
    case 2:
      return <Award className="w-5 h-5 text-amber-500 drop-shadow-lg" />
    default:
      return <Target className="w-4 h-4 text-[#8ab4ff]" />
  }
}

const getRankColor = (index: number) => {
  switch (index) {
    case 0: return 'from-yellow-700/20 to-yellow-800/20 border-yellow-500/30'
    case 1: return 'from-gray-600/20 to-gray-700/20 border-gray-400/30'
    case 2: return 'from-amber-700/20 to-amber-800/20 border-amber-500/30'
    default: return 'from-[#0f1620] to-[#0c1320] border-[#0087FF]/20'
  }
}

const getVipBadge = (vipLevel: number, dashboardT?: any) => {
  const vipMap: Record<number, { label: string, classes: string }> = {
    0: { label: dashboardT ? dashboardT('vip.noVip') : 'No VIP', classes: 'text-gray-300 border-gray-600/50 bg-gradient-to-r from-gray-800/40 to-gray-700/30' },
    1: { label: dashboardT ? dashboardT('vip.silver') : 'Silver', classes: 'text-slate-200 border-slate-400/40 bg-gradient-to-r from-slate-600/40 to-slate-700/30' },
    2: { label: dashboardT ? dashboardT('vip.gold') : 'Gold', classes: 'text-amber-200 border-amber-400/40 bg-gradient-to-r from-amber-600/30 to-amber-500/20' },
    3: { label: dashboardT ? dashboardT('vip.diamond') : 'Diamond', classes: 'text-cyan-200 border-cyan-400/40 bg-gradient-to-r from-cyan-600/30 to-blue-600/20' },
  }
  
  const vip = vipMap[vipLevel] || vipMap[0]
  
  if (vipLevel === 0) return null
  
  return (
    <span className={`inline-flex items-center gap-2 px-3 py-1 rounded-xl text-xs font-semibold border ${vip.classes}`}>
      <svg viewBox="0 0 24 24" className={`w-4 h-4 ${vipLevel===2?'text-amber-300':vipLevel===3?'text-cyan-300':'text-slate-200'}`} fill="currentColor">
        <path d="M12 2l3 6 6 .9-4.5 4.3L17 20l-5-2.6L7 20l1.5-6.8L4 8.9 10 8l2-6z"/>
      </svg>
      {vip.label}
    </span>
  )
}

export default function MoneyLeaderboard({ limit = 5, className = "" }: MoneyLeaderboardProps) {
  const t = useTranslations('leaderboard')
  const dashboardT = useTranslations('dashboard')
  const [leaderboard, setLeaderboard] = useState<LeaderboardEntry[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    fetchLeaderboard()
  }, [limit])

  const fetchLeaderboard = async () => {
    try {
      setLoading(true)
      const response = await fetch(`/api/leaderboard/money?limit=${limit}`)

      if (response.ok) {
        const data = await response.json()
        const entries = data.leaderboard || []

        // Fetch profile photos for each entry
        const entriesWithPhotos = await Promise.all(
          entries.map(async (entry: LeaderboardEntry) => {
            try {
              const photoResponse = await fetch(`/api/user/upload-photo?userId=${entry.accountId}`)
              if (photoResponse.ok) {
                const photoData = await photoResponse.json()
                if (photoData?.photo?.data && photoData?.photo?.type) {
                  entry.profilePhoto = `data:${photoData.photo.type};base64,${photoData.photo.data}`
                }
              }
            } catch (error) {
              console.error('Error fetching profile photo for user', entry.accountId, error)
            }
            return entry
          })
        )

        setLeaderboard(entriesWithPhotos)
      } else {
        setError(t('error'))
      }
    } catch (error) {
      setError(t('error'))
      console.error('Error fetching leaderboard:', error)
    } finally {
      setLoading(false)
    }
  }

  if (loading) {
    return (
      <div className={`rounded-2xl p-3 border border-[#0090ff]/20 bg-gradient-to-br from-[#0b1422]/90 to-[#0a1120]/90 backdrop-blur-md shadow-[0_0_40px_-16px_rgba(0,135,255,0.35)] ${className}`}>
        <div className="text-center py-6">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-[#53b1ff] mx-auto mb-3"></div>
          <p className="text-[#b8d8ff] text-sm">{t('loading')}</p>
        </div>
      </div>
    )
  }

  if (error) {
    return (
      <div className={`rounded-2xl p-3 border border-rose-500/30 bg-gradient-to-br from-[#1a0f14]/90 to-[#160d12]/90 backdrop-blur-md ${className}`}>
        <div className="text-center py-6">
          <p className="text-rose-300 mb-2 text-sm">{t('error')}</p>
          <button
            onClick={fetchLeaderboard}
            className="text-xs text-[#a9c7ff] hover:text-white transition-colors"
          >
            {t('tryAgain')}
          </button>
        </div>
      </div>
    )
  }

  if (leaderboard.length === 0) {
    return (
      <div className={`rounded-2xl p-3 border border-[#0090ff]/20 bg-gradient-to-br from-[#0b1422]/90 to-[#0a1120]/90 backdrop-blur-md shadow-[0_0_40px_-16px_rgba(0,135,255,0.35)] ${className}`}>
        <div className="text-center py-6">
          <div className="w-12 h-12 bg-[#0e223f]/60 rounded-2xl flex items-center justify-center mx-auto mb-3 border border-[#1c3e6e]/50">
            <Trophy className="w-6 h-6 text-[#94c2ff]" />
          </div>
          <h3 className="text-lg font-semibold text-white mb-2">{t('noData')}</h3>
          <p className="text-[#9cbdf5] text-sm">{t('noDataDesc')}</p>
        </div>
      </div>
    )
  }

  return (
    <div className={`rounded-2xl p-3 border border-[#0090ff]/20 bg-gradient-to-br from-[#0b1422]/90 to-[#0a1120]/90 backdrop-blur-md shadow-[0_0_40px_-16px_rgba(0,135,255,0.35)] ${className}`}>
      {/* Header */}
      <div className="text-center mb-4">
        <div className="w-11 h-11 bg-gradient-to-br from-[#0e223f]/80 to-[#1a3a5c]/80 rounded-2xl flex items-center justify-center mx-auto mb-2 border border-[#1c3e6e]/60 shadow-lg">
          <Trophy className="w-5 h-5 text-[#bcd7ff] drop-shadow-lg" />
        </div>
        <h3 className="text-base font-bold text-white mb-1">{t('title')}</h3>
        <p className="text-[#9cbdf5] text-xs">{t('subtitle')}</p>
        <div className="w-12 h-0.5 bg-gradient-to-r from-[#53b1ff] to-[#64e1ff] rounded-full mx-auto mt-2"></div>
      </div>

      {/* Leaderboard Entries */}
      <div className="space-y-2">
        {leaderboard.map((entry, index) => (
          <div
            key={entry.accountId}
            className={`group relative bg-gradient-to-br ${getRankColor(index)} rounded-2xl p-4 border border-[#0087FF]/20 hover:border-[#0087FF]/40 transition-all duration-300 hover:shadow-xl hover:shadow-[#0087FF]/20 hover:-translate-y-0.5 focus:outline-none focus:ring-2 focus:ring-[#0087FF]/40 w-full text-left`}
          >
            <div className="flex items-center justify-between">
              {/* Left side - Rank and Profile */}
              <div className="flex items-center gap-4">
                <div className="flex items-center justify-center w-8 h-8 rounded-2xl bg-[#0e223f]/60 border border-[#1c3e6e]/60">
                  {getRankIcon(index)}
                </div>

                <div className="flex items-center gap-3">
                  {/* Profile Photo */}
                  <div className="w-10 h-10 rounded-full overflow-hidden border border-[#0087FF]/30 flex-shrink-0">
                    {entry.profilePhoto ? (
                      <img
                        src={entry.profilePhoto}
                        alt={entry.accountName}
                        className="w-full h-full object-cover"
                        onError={(e) => {
                          const target = e.currentTarget as HTMLImageElement
                          target.style.display = 'none'
                          const fallback = target.nextElementSibling as HTMLElement
                          if (fallback) fallback.style.display = 'flex'
                        }}
                      />
                    ) : null}
                    <div className={`w-full h-full bg-gradient-to-br from-[#0087FF]/20 to-[#8ab4ff]/10 flex items-center justify-center ${entry.profilePhoto ? 'hidden' : 'flex'}`}>
                      <img
                        src="/images/logo.webp"
                        alt="Server Logo"
                        className="w-6 h-6 object-contain opacity-80"
                        onError={(e) => {
                          const target = e.currentTarget as HTMLImageElement
                          target.style.display = 'none'
                          const fallback = target.nextElementSibling as HTMLElement
                          if (fallback) fallback.style.display = 'flex'
                        }}
                      />
                      <User className="w-5 h-5 text-[#8ab4ff] hidden" />
                    </div>
                  </div>

                  <div className="min-w-0">
                    <div className="flex items-center gap-1 flex-wrap">
                      <h4 className="text-sm font-bold text-white truncate group-hover:text-[#8ab4ff] transition-colors">
                        {entry.accountName}
                      </h4>
                      {getVipBadge(entry.vip, dashboardT)}
                    </div>
                    <p className="text-xs text-[#8fb8ff] flex items-center gap-1">
                      <Target className="w-2 h-2" /> {entry.accountId}
                    </p>
                  </div>
                </div>
              </div>

              {/* Right side - Money */}
              <div className="text-right">
                <div className="flex items-center gap-1 mb-0.5">
                  <Coins className="w-3 h-3 text-emerald-400 drop-shadow-sm" />
                  <p className="text-sm font-bold text-emerald-400">{formatMoney(entry.totalMoney)}</p>
                </div>
                <div className="flex items-center gap-1 justify-end">
                  <Flame className="w-2 h-2 text-orange-400" />
                  <p className="text-xs text-[#8fb8ff]">#{index + 1}</p>
                </div>
              </div>
            </div>

            {/* Hover effect overlay */}
            <div className="absolute inset-0 rounded-2xl bg-gradient-to-br from-[#0087FF]/5 to-transparent opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none" />
          </div>
        ))}
      </div>

       {/* Footer Stats */}
       <div className="mt-4 pt-3 border-t border-[#0f2545]/60">
         <div className="grid grid-cols-2 gap-3 text-center">
           <div className="rounded-xl p-3 border border-[#0f2545]/60 bg-[#0c1627]/60">
             <div className="flex items-center justify-center gap-2 mb-1">
               <Wallet className="w-4 h-4 text-emerald-400" />
               <p className="text-xl font-bold text-emerald-400">
                 {formatMoney(leaderboard.reduce((sum, entry) => sum + entry.totalMoney, 0))}
               </p>
             </div>
             <p className="text-[#9cbdf5] text-xs">{t('topWealth')}</p>
           </div>
           <div className="rounded-xl p-3 border border-[#0f2545]/60 bg-[#0c1627]/60">
             <div className="flex items-center justify-center gap-2 mb-1">
               <Users className="w-4 h-4 text-cyan-300" />
               <p className="text-xl font-bold text-cyan-300">
                 {leaderboard.reduce((sum, entry) => sum + entry.characterCount, 0)}
               </p>
             </div>
             <p className="text-[#9cbdf5] text-xs">{t('topCharacters')}</p>
           </div>
         </div>
       </div>
    </div>
  )
}
