import { useQuery } from '@tanstack/react-query'
import { getMyAchievements, getMyStats } from '../../api/gamification'
import { formatDistanceToNow } from 'date-fns'
import type { UserAchievement } from '../../types/gamification'

const RARITY_COLORS: Record<string, string> = {
  common: 'border-gray-300 bg-gray-50',
  rare: 'border-blue-400 bg-blue-50',
  epic: 'border-purple-400 bg-purple-50',
  legendary: 'border-yellow-400 bg-yellow-50',
}

const RARITY_GLOW: Record<string, string> = {
  common: '',
  rare: 'shadow-blue-100',
  epic: 'shadow-purple-100 shadow-md',
  legendary: 'shadow-yellow-200 shadow-lg',
}

interface AchievementsProps {
  showStreaks?: boolean
}

export default function Achievements({ showStreaks = true }: AchievementsProps) {
  const { data: achievements = [], isLoading: loadingAchievements } = useQuery({
    queryKey: ['my-achievements'],
    queryFn: getMyAchievements,
    retry: 1,
  })

  const { data: stats, isLoading: loadingStats } = useQuery({
    queryKey: ['my-stats'],
    queryFn: getMyStats,
    retry: 1,
  })

  const isLoading = loadingAchievements || loadingStats

  return (
    <div className="bg-white rounded-xl shadow-sm p-6">
      {/* Streaks Section */}
      {showStreaks && stats && (
        <div className="mb-6">
          <h3 className="text-lg font-bold text-gray-900 mb-4 flex items-center gap-2">
            <span className="text-2xl">🔥</span> Streaks
          </h3>
          <div className="grid grid-cols-2 gap-3">
            <div className="bg-gray-50 rounded-lg p-3 text-center border">
              <div className="text-3xl mb-1">
                {stats.current_win_streak > 0 ? '🔥' : '❄️'}
              </div>
              <p className="text-2xl font-bold text-gray-900">{stats.current_win_streak}</p>
              <p className="text-xs text-gray-500">Current Win Streak</p>
            </div>
            <div className="bg-gray-50 rounded-lg p-3 text-center border">
              <div className="text-3xl mb-1">🏆</div>
              <p className="text-2xl font-bold text-yellow-600">{stats.best_win_streak}</p>
              <p className="text-xs text-gray-500">Best Win Streak</p>
            </div>
            <div className="bg-gray-50 rounded-lg p-3 text-center border">
              <div className="text-3xl mb-1">📅</div>
              <p className="text-2xl font-bold text-green-600">{stats.consecutive_days_betting}</p>
              <p className="text-xs text-gray-500">Day Streak</p>
            </div>
            <div className="bg-gray-50 rounded-lg p-3 text-center border">
              <div className="text-3xl mb-1">👥</div>
              <p className="text-2xl font-bold text-blue-600">{stats.unique_opponents}</p>
              <p className="text-xs text-gray-500">Unique Opponents</p>
            </div>
          </div>
        </div>
      )}

      {/* Achievements Section */}
      <h3 className="text-lg font-bold text-gray-900 mb-4 flex items-center gap-2">
        <span className="text-2xl">🎖️</span> Achievements
        {achievements.length > 0 && (
          <span className="text-sm font-normal text-gray-500">({achievements.length} earned)</span>
        )}
      </h3>

      {isLoading ? (
        <div className="grid grid-cols-2 gap-3">
          {[...Array(4)].map((_, i) => (
            <div key={i} className="h-20 bg-gray-100 rounded-lg animate-pulse" />
          ))}
        </div>
      ) : achievements.length === 0 ? (
        <div className="text-center py-6">
          <p className="text-4xl mb-2">🎯</p>
          <p className="text-gray-500">No achievements yet</p>
          <p className="text-sm text-gray-400">Start betting to unlock achievements!</p>
        </div>
      ) : (
        <div className="grid grid-cols-2 gap-3">
          {achievements.map((ua: UserAchievement) => (
            <div
              key={ua.id}
              className={`border rounded-lg p-3 ${RARITY_COLORS[ua.achievement.rarity]} ${RARITY_GLOW[ua.achievement.rarity]}`}
            >
              <div className="flex items-center gap-2 mb-1">
                <span className="text-2xl">{ua.achievement.icon}</span>
                <div className="min-w-0 flex-1">
                  <p className="text-gray-900 font-medium text-sm truncate">
                    {ua.achievement.name}
                  </p>
                  <p className="text-xs text-green-600">+{ua.achievement.xp_reward} XP</p>
                </div>
              </div>
              <p className="text-xs text-gray-600 line-clamp-2">
                {ua.achievement.description}
              </p>
              <p className="text-xs text-gray-400 mt-1">
                {formatDistanceToNow(new Date(ua.earned_at), { addSuffix: true })}
              </p>
            </div>
          ))}
        </div>
      )}
    </div>
  )
}
