import { useState, useEffect } from 'react'
import { Link } from 'react-router-dom'
import { useShopStore } from '@/store/shop'
import { useToast } from '@/store/toast'
import { useConfirm } from '@/store/confirm'
import { GlassCard, NeonButton, FramePreview } from '@/components/ui'
import {
  Loader2, Coins, ShoppingBag, Package, Sparkles,
  Frame, Type, Palette, Image, Zap, SkipForward,
  Minus, Plus, Shuffle, Dice5, Copy, Undo2
} from 'lucide-react'
import type { ShopItem, ShopItemType, ShopItemPublic } from '@/types'
import { RARITY_COLORS, RARITY_NAMES } from '@/types'
import clsx from 'clsx'

const ITEM_TYPE_ICONS: Record<ShopItemType, React.ReactNode> = {
  frame: <Frame className="w-5 h-5" />,
  title: <Type className="w-5 h-5" />,
  name_color: <Palette className="w-5 h-5" />,
  background: <Image className="w-5 h-5" />,
  consumable: <Zap className="w-5 h-5" />,
}

const CONSUMABLE_ICONS: Record<string, React.ReactNode> = {
  skip: <SkipForward className="w-8 h-8" />,
  boost: <Zap className="w-8 h-8" />,
  wild_card: <Shuffle className="w-8 h-8" />,
  lucky_dice: <Dice5 className="w-8 h-8" />,
  copycat: <Copy className="w-8 h-8" />,
  undo: <Undo2 className="w-8 h-8" />,
}

interface ShopItemCardProps {
  item: ShopItem
  onPurchase: (item: ShopItem, quantity: number) => void
  isPurchasing: boolean
}

function ShopItemCard({ item, onPurchase, isPurchasing }: ShopItemCardProps) {
  const [quantity, setQuantity] = useState(1)
  const rarityColors = RARITY_COLORS[item.rarity]
  const isConsumable = item.item_type === 'consumable'
  const maxQuantity = item.stock_remaining !== null ? Math.min(10, item.stock_remaining) : 10
  const totalPrice = item.price * quantity

  const incrementQuantity = () => {
    if (quantity < maxQuantity) {
      setQuantity(q => q + 1)
    }
  }

  const decrementQuantity = () => {
    if (quantity > 1) {
      setQuantity(q => q - 1)
    }
  }

  const getItemPreview = () => {
    if (item.item_type === 'consumable') {
      return CONSUMABLE_ICONS[item.code] || <Package className="w-8 h-8" />
    }

    // Name color preview - handles solid, gradient, animated
    if (item.item_type === 'name_color') {
      const data = item.asset_data as { style?: string; color?: string; gradient?: string[]; animation?: string } | null

      // Gradient style
      if (data?.style === 'gradient' && data.gradient) {
        return (
          <div
            className="w-12 h-12 rounded-full border-2 border-dark-600"
            style={{ background: `linear-gradient(135deg, ${data.gradient.join(', ')})` }}
          />
        )
      }

      // Animated rainbow style
      if (data?.style === 'animated') {
        return (
          <div
            className="w-12 h-12 rounded-full border-2 border-dark-600 animate-rainbow-rotate"
            style={{
              background: 'linear-gradient(135deg, #ff0000, #ff7f00, #ffff00, #00ff00, #0000ff, #9400d3, #ff0000)',
              backgroundSize: '400% 400%'
            }}
          />
        )
      }

      // Solid color style (default)
      const solidColor = data?.color || '#ffffff'
      return (
        <div
          className="w-12 h-12 rounded-full border-2 border-dark-600"
          style={{ backgroundColor: solidColor }}
        />
      )
    }

    // Background preview
    if (item.item_type === 'background') {
      const data = item.asset_data as { type?: string; color?: string; gradient?: string[]; pattern?: string; animation?: string } | null
      let bgStyle: React.CSSProperties = {}
      let animClass = ''

      if (data?.type === 'solid' && data.color) {
        bgStyle = { backgroundColor: data.color }
      } else if (data?.type === 'gradient' && data.gradient) {
        bgStyle = { background: `linear-gradient(135deg, ${data.gradient.join(', ')})` }
      } else if (data?.type === 'pattern') {
        if (data.pattern === 'stars') {
          bgStyle = {
            background: `
              radial-gradient(1px 1px at 10px 10px, #fff, transparent),
              radial-gradient(1px 1px at 30px 25px, rgba(255,255,255,0.8), transparent),
              radial-gradient(1px 1px at 50px 15px, #fff, transparent),
              linear-gradient(135deg, #0d1b2a 0%, #1b263b 100%)
            `,
            backgroundSize: '60px 40px, 60px 40px, 60px 40px, 100% 100%'
          }
          animClass = 'animate-twinkle'
        } else if (data.pattern === 'gaming-icons') {
          bgStyle = {
            background: `
              linear-gradient(45deg, rgba(34,211,238,0.2) 25%, transparent 25%),
              linear-gradient(-45deg, rgba(168,85,247,0.2) 25%, transparent 25%),
              linear-gradient(135deg, #0f172a 0%, #1e1b4b 100%)
            `,
            backgroundSize: '20px 20px, 20px 20px, 100% 100%'
          }
        }
      } else if (data?.type === 'animated' && data.animation === 'fire-particles') {
        bgStyle = {
          background: `
            radial-gradient(circle at 50% 100%, rgba(255,100,0,0.5) 0%, transparent 50%),
            radial-gradient(circle at 30% 80%, rgba(255,50,0,0.4) 0%, transparent 40%),
            linear-gradient(to top, #1a0a00 0%, #0d0d0d 100%)
          `
        }
        animClass = 'animate-fire-pulse'
      }

      return (
        <div
          className={clsx('w-16 h-12 rounded-lg border-2 border-dark-600', animClass)}
          style={bgStyle}
        />
      )
    }

    if (item.item_type === 'frame') {
      // Use FramePreview for animated and gradient frames
      const frameItem: ShopItemPublic = {
        id: item.id,
        code: item.code,
        name: item.name,
        item_type: item.item_type,
        rarity: item.rarity,
        asset_data: item.asset_data,
      }
      return <FramePreview frame={frameItem} size="lg" />
    }
    if (item.item_type === 'title' && item.asset_data?.text) {
      return (
        <span
          className="text-lg font-bold"
          style={{ color: (item.asset_data.color as string) || '#ffffff' }}
        >
          {item.asset_data.text as string}
        </span>
      )
    }
    return ITEM_TYPE_ICONS[item.item_type]
  }

  return (
    <GlassCard
      className={clsx(
        'p-4 border transition-all duration-300',
        rarityColors.border,
        item.is_owned && !isConsumable && 'opacity-60'
      )}
    >
      {/* Rarity badge */}
      <div className={clsx('text-xs font-medium mb-2', rarityColors.text)}>
        {RARITY_NAMES[item.rarity]}
      </div>

      {/* Item preview */}
      <div className="flex justify-center items-center h-20 mb-3">
        {getItemPreview()}
      </div>

      {/* Item info */}
      <h3 className="text-white font-semibold text-center mb-1">{item.name}</h3>
      <p className="text-gray-400 text-xs text-center mb-3 line-clamp-2">
        {item.description}
      </p>

      {/* Quantity selector for consumables */}
      {isConsumable && item.is_available && (
        <div className="flex items-center justify-center gap-2 mb-3">
          <button
            onClick={decrementQuantity}
            disabled={quantity <= 1 || isPurchasing}
            className="w-7 h-7 rounded-lg bg-dark-700 hover:bg-dark-600 disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center text-gray-400 hover:text-white transition-colors"
          >
            <Minus className="w-4 h-4" />
          </button>
          <span className="w-8 text-center text-white font-bold">{quantity}</span>
          <button
            onClick={incrementQuantity}
            disabled={quantity >= maxQuantity || isPurchasing}
            className="w-7 h-7 rounded-lg bg-dark-700 hover:bg-dark-600 disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center text-gray-400 hover:text-white transition-colors"
          >
            <Plus className="w-4 h-4" />
          </button>
        </div>
      )}

      {/* Price and action */}
      <div className="flex items-center justify-between mt-auto">
        <div className="flex items-center gap-1 text-yellow-400">
          <Coins className="w-4 h-4" />
          <span className="font-bold">{isConsumable ? totalPrice : item.price}</span>
          {isConsumable && quantity > 1 && (
            <span className="text-xs text-gray-500">({item.price}×{quantity})</span>
          )}
        </div>

        {item.is_owned && !isConsumable ? (
          <span className="text-green-400 text-sm flex items-center gap-1">
            <Sparkles className="w-4 h-4" />
            Куплено
          </span>
        ) : item.is_equipped ? (
          <span className="text-neon-400 text-sm">Надето</span>
        ) : (
          <NeonButton
            size="sm"
            onClick={() => onPurchase(item, isConsumable ? quantity : 1)}
            disabled={isPurchasing || !item.is_available}
          >
            {isPurchasing ? (
              <Loader2 className="w-4 h-4 animate-spin" />
            ) : (
              'Купить'
            )}
          </NeonButton>
        )}
      </div>

      {/* Stock info */}
      {item.stock_remaining !== null && (
        <div className="text-xs text-gray-500 text-center mt-2">
          Осталось: {item.stock_remaining}
        </div>
      )}
    </GlassCard>
  )
}

export function ShopPage() {
  const { items, balance, isLoading, loadItems, loadBalance, purchase, clearError, error } = useShopStore()
  const toast = useToast()
  const confirm = useConfirm()

  const [activeTab, setActiveTab] = useState<ShopItemType | 'all'>('all')
  const [purchasingId, setPurchasingId] = useState<number | null>(null)

  useEffect(() => {
    loadBalance()
    loadItems()
  }, [loadBalance, loadItems])

  useEffect(() => {
    if (error) {
      toast.error(error)
      clearError()
    }
  }, [error, toast, clearError])

  const handlePurchase = async (item: ShopItem, quantity: number = 1) => {
    const totalCost = item.price * quantity
    const isConsumable = item.item_type === 'consumable'
    const quantityText = quantity > 1 ? ` (×${quantity})` : ''

    const confirmed = await confirm({
      title: 'Подтвердите покупку',
      message: isConsumable && quantity > 1
        ? `Купить "${item.name}" × ${quantity} шт. за ${totalCost} монет?`
        : `Купить "${item.name}" за ${item.price} монет?`,
      confirmText: 'Купить',
      cancelText: 'Отмена',
    })

    if (!confirmed) return

    setPurchasingId(item.id)
    const success = await purchase(item.id, quantity)
    setPurchasingId(null)

    if (success) {
      toast.success(`Вы приобрели "${item.name}"${quantityText}!`)
    }
  }

  const filteredItems = activeTab === 'all'
    ? items
    : items.filter(item => item.item_type === activeTab)

  // Group items by type for "All" tab
  const itemsByType: Record<ShopItemType, ShopItem[]> = {
    frame: [],
    title: [],
    name_color: [],
    background: [],
    consumable: [],
  }

  if (activeTab === 'all') {
    items.forEach(item => {
      if (itemsByType[item.item_type]) {
        itemsByType[item.item_type].push(item)
      }
    })
  }

  const categoryOrder: ShopItemType[] = ['frame', 'title', 'name_color', 'background', 'consumable']
  const categoryLabels: Record<ShopItemType, { label: string; icon: React.ReactNode }> = {
    frame: { label: 'Рамки профиля', icon: <Frame className="w-5 h-5" /> },
    title: { label: 'Титулы', icon: <Type className="w-5 h-5" /> },
    name_color: { label: 'Цвета ника', icon: <Palette className="w-5 h-5" /> },
    background: { label: 'Фоны профиля', icon: <Image className="w-5 h-5" /> },
    consumable: { label: 'Расходуемые предметы', icon: <Zap className="w-5 h-5" /> },
  }

  const tabs: { id: ShopItemType | 'all'; label: string; icon: React.ReactNode }[] = [
    { id: 'all', label: 'Все', icon: <ShoppingBag className="w-4 h-4" /> },
    { id: 'frame', label: 'Рамки', icon: <Frame className="w-4 h-4" /> },
    { id: 'title', label: 'Титулы', icon: <Type className="w-4 h-4" /> },
    { id: 'name_color', label: 'Цвета', icon: <Palette className="w-4 h-4" /> },
    { id: 'background', label: 'Фоны', icon: <Image className="w-4 h-4" /> },
    { id: 'consumable', label: 'Расходники', icon: <Zap className="w-4 h-4" /> },
  ]

  if (isLoading && items.length === 0) {
    return (
      <div className="flex items-center justify-center min-h-[60vh]">
        <Loader2 className="w-12 h-12 animate-spin text-neon-500" />
      </div>
    )
  }

  return (
    <div className="max-w-6xl mx-auto px-4 py-6">
      {/* Header */}
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-3xl font-bold text-white flex items-center gap-3">
            <ShoppingBag className="w-8 h-8 text-neon-500" />
            Магазин
          </h1>
          <p className="text-gray-400 mt-1">
            Покупай косметику и расходуемые предметы
          </p>
        </div>

        <div className="flex items-center gap-4">
          {/* Balance */}
          <div className="flex items-center gap-2 px-4 py-2 bg-dark-800/50 rounded-lg border border-yellow-500/30">
            <Coins className="w-5 h-5 text-yellow-400" />
            <span className="text-yellow-400 font-bold text-lg">{balance}</span>
          </div>

          {/* Link to inventory */}
          <Link to="/inventory">
            <NeonButton variant="secondary">
              <Package className="w-4 h-4 mr-2" />
              Инвентарь
            </NeonButton>
          </Link>
        </div>
      </div>

      {/* Tabs */}
      <div className="flex gap-2 mb-6 overflow-x-auto pb-2">
        {tabs.map(tab => (
          <button
            key={tab.id}
            onClick={() => setActiveTab(tab.id)}
            className={clsx(
              'flex items-center gap-2 px-4 py-2 rounded-lg font-medium transition-all whitespace-nowrap',
              activeTab === tab.id
                ? 'bg-neon-500 text-dark-900'
                : 'bg-dark-700 text-gray-300 hover:bg-dark-600'
            )}
          >
            {tab.icon}
            {tab.label}
          </button>
        ))}
      </div>

      {/* Items grid */}
      {filteredItems.length === 0 ? (
        <GlassCard className="p-8 text-center">
          <Package className="w-16 h-16 mx-auto text-gray-500 mb-4" />
          <p className="text-gray-400">Нет доступных товаров в этой категории</p>
        </GlassCard>
      ) : activeTab === 'all' ? (
        // Grouped view for "All" tab
        <div className="space-y-8">
          {categoryOrder.map(category => {
            const categoryItems = itemsByType[category]
            if (categoryItems.length === 0) return null

            const { label, icon } = categoryLabels[category]

            return (
              <div key={category}>
                <div className="flex items-center gap-2 mb-4">
                  <div className="w-8 h-8 rounded-lg bg-neon-500/20 flex items-center justify-center text-neon-400">
                    {icon}
                  </div>
                  <h2 className="text-lg font-semibold text-white">{label}</h2>
                  <span className="text-sm text-gray-500">({categoryItems.length})</span>
                </div>
                <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
                  {categoryItems.map(item => (
                    <ShopItemCard
                      key={item.id}
                      item={item}
                      onPurchase={handlePurchase}
                      isPurchasing={purchasingId === item.id}
                    />
                  ))}
                </div>
              </div>
            )
          })}
        </div>
      ) : (
        // Regular grid for specific category
        <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
          {filteredItems.map(item => (
            <ShopItemCard
              key={item.id}
              item={item}
              onPurchase={handlePurchase}
              isPurchasing={purchasingId === item.id}
            />
          ))}
        </div>
      )}

      {/* Info about coins */}
      <GlassCard className="mt-8 p-4">
        <h3 className="text-white font-semibold mb-2 flex items-center gap-2">
          <Coins className="w-5 h-5 text-yellow-400" />
          Как заработать монеты?
        </h3>
        <ul className="text-gray-400 text-sm space-y-1">
          <li>• Выполняй задания в <span className="text-neon-400">сертифицированных</span> марафонах</li>
          <li>• Easy задание — 10 монет, Medium — 20 монет, Hard — 35 монет</li>
          <li>• Playthrough — ~10% от заработанных очков</li>
          <li>• Топ-3 места в марафоне: 1-е — 500, 2-е — 250, 3-е — 150 монет</li>
        </ul>
      </GlassCard>
    </div>
  )
}
