import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { getMyLootBoxes, openLootBox } from '../../api/gamification'
import type { LootBox, LootBoxRarity, LootBoxOpenResult } from '../../types/gamification'

const RARITY_CONFIG: Record<LootBoxRarity, { color: string; bg: string; border: string; icon: string }> = {
  common: {
    color: 'text-gray-600',
    bg: 'bg-gray-100',
    border: 'border-gray-300',
    icon: '📦',
  },
  uncommon: {
    color: 'text-green-600',
    bg: 'bg-green-50',
    border: 'border-green-300',
    icon: '🎁',
  },
  rare: {
    color: 'text-blue-600',
    bg: 'bg-blue-50',
    border: 'border-blue-300',
    icon: '💎',
  },
  epic: {
    color: 'text-purple-600',
    bg: 'bg-purple-50',
    border: 'border-purple-300',
    icon: '👑',
  },
  legendary: {
    color: 'text-yellow-600',
    bg: 'bg-yellow-50',
    border: 'border-yellow-400',
    icon: '🌟',
  },
}

const REWARD_ICONS: Record<string, string> = {
  bonus_cash: '💰',
  xp_boost: '⚡',
  fee_reduction: '📉',
  free_bet: '🎟️',
  avatar_frame: '🖼️',
  badge: '🏅',
  nothing: '💨',
}

export default function Airdrops() {
  const queryClient = useQueryClient()
  const [openingId, setOpeningId] = useState<number | null>(null)
  const [result, setResult] = useState<LootBoxOpenResult | null>(null)
  const [showResult, setShowResult] = useState(false)

  const { data: airdrops = [], isLoading } = useQuery({
    queryKey: ['my-loot-boxes'],
    queryFn: getMyLootBoxes,
    retry: 1,
  })

  const openMutation = useMutation({
    mutationFn: openLootBox,
    onSuccess: (data) => {
      setResult(data)
      setShowResult(true)
      queryClient.invalidateQueries({ queryKey: ['my-loot-boxes'] })
      queryClient.invalidateQueries({ queryKey: ['my-stats'] })
    },
    onSettled: () => {
      setOpeningId(null)
    },
  })

  const unclaimedAirdrops = airdrops.filter((box: LootBox) => !box.opened)

  const handleClaim = (box: LootBox) => {
    setOpeningId(box.id)
    setResult(null)
    setShowResult(false)
    openMutation.mutate(box.id)
  }

  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> Airdrops
        {unclaimedAirdrops.length > 0 && (
          <span className="bg-red-500 text-white text-xs px-2 py-0.5 rounded-full">
            {unclaimedAirdrops.length}
          </span>
        )}
      </h3>

      {/* Result Modal */}
      {showResult && result && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-2xl p-6 max-w-sm w-full text-center shadow-xl">
            <div className="text-6xl mb-4">{REWARD_ICONS[result.reward_type] || '🪂'}</div>
            <h4 className="text-xl font-bold text-gray-900 mb-2">
              {result.reward_type === 'nothing' ? 'Better luck next time!' : 'You received:'}
            </h4>
            <p className="text-2xl font-bold text-green-600 mb-2">{result.reward_value}</p>
            <p className="text-gray-600 mb-4">{result.message}</p>
            <button
              onClick={() => setShowResult(false)}
              className="bg-primary hover:bg-primary/90 text-white px-6 py-2 rounded-lg font-medium transition-colors"
            >
              Awesome!
            </button>
          </div>
        </div>
      )}

      {isLoading ? (
        <div className="grid grid-cols-3 gap-3">
          {[...Array(3)].map((_, i) => (
            <div key={i} className="h-24 bg-gray-100 rounded-lg animate-pulse" />
          ))}
        </div>
      ) : unclaimedAirdrops.length === 0 ? (
        <div className="text-center py-6">
          <p className="text-4xl mb-2">🪂</p>
          <p className="text-gray-500">No airdrops available</p>
          <p className="text-sm text-gray-400">Earn them through achievements & VIP level ups!</p>
        </div>
      ) : (
        <div className="grid grid-cols-3 gap-3">
          {unclaimedAirdrops.map((box: LootBox) => {
            const config = RARITY_CONFIG[box.rarity]
            const isOpening = openingId === box.id

            return (
              <button
                key={box.id}
                onClick={() => handleClaim(box)}
                disabled={isOpening || openMutation.isPending}
                className={`${config.bg} ${config.border} border-2 rounded-lg p-3 text-center transition-all hover:scale-105 disabled:opacity-50 disabled:hover:scale-100`}
              >
                <div className={`text-3xl mb-1 ${isOpening ? 'animate-spin' : 'animate-bounce'}`}>
                  {isOpening ? '🎰' : config.icon}
                </div>
                <p className={`text-xs font-medium capitalize ${config.color}`}>
                  {box.rarity}
                </p>
                <p className="text-xs text-gray-400 truncate">{box.source}</p>
              </button>
            )
          })}
        </div>
      )}

      {/* Claimed History (collapsed) */}
      {airdrops.filter((b: LootBox) => b.opened).length > 0 && (
        <details className="mt-4">
          <summary className="text-sm text-gray-500 cursor-pointer hover:text-gray-700">
            View claimed airdrops ({airdrops.filter((b: LootBox) => b.opened).length})
          </summary>
          <div className="mt-2 space-y-1 max-h-32 overflow-y-auto">
            {airdrops
              .filter((b: LootBox) => b.opened)
              .map((box: LootBox) => (
                <div key={box.id} className="flex items-center gap-2 text-xs text-gray-500">
                  <span>{RARITY_CONFIG[box.rarity].icon}</span>
                  <span className="capitalize">{box.rarity}</span>
                  <span>→</span>
                  <span>{box.reward_value || 'Nothing'}</span>
                </div>
              ))}
          </div>
        </details>
      )}
    </div>
  )
}
