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

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 InventoryItemCardProps {
  inventoryItem: InventoryItem
  onEquip: (inventoryId: number) => void
  onUnequip: (itemType: ShopItemType) => void
  isProcessing: boolean
}

function InventoryItemCard({ inventoryItem, onEquip, onUnequip, isProcessing }: InventoryItemCardProps) {
  const { item, quantity, equipped } = inventoryItem
  const rarityColors = RARITY_COLORS[item.rarity]

  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

      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(', ')})` }}
          />
        )
      }
      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%'
            }}
          />
        )
      }
      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),
              linear-gradient(135deg, #0d1b2a 0%, #1b263b 100%)
            `,
            backgroundSize: '50px 35px, 50px 35px, 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: '15px 15px, 15px 15px, 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%),
            linear-gradient(to top, #1a0a00 0%, #0d0d0d 100%)
          `
        }
        animClass = 'animate-fire-pulse'
      }

      return (
        <div
          className={`w-14 h-10 rounded-lg border-2 border-dark-600 ${animClass}`}
          style={bgStyle}
        />
      )
    }

    if (item.item_type === 'frame') {
      return <FramePreview frame={item} 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 <Package className="w-8 h-8 text-gray-400" />
  }

  const isCosmetic = item.item_type !== 'consumable'

  return (
    <GlassCard
      className={clsx(
        'p-4 border transition-all duration-300',
        equipped ? 'border-neon-500 bg-neon-500/10' : rarityColors.border
      )}
    >
      {/* Equipped badge */}
      {equipped && (
        <div className="flex items-center gap-1 text-neon-400 text-xs font-medium mb-2">
          <Check className="w-3 h-3" />
          Надето
        </div>
      )}

      {/* Rarity badge */}
      {!equipped && (
        <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-16 mb-3">
        {getItemPreview()}
      </div>

      {/* Item info */}
      <h3 className="text-white font-semibold text-center mb-1">{item.name}</h3>
      <p className="text-gray-500 text-xs text-center mb-1">
        {ITEM_TYPE_NAMES[item.item_type]}
      </p>

      {/* Quantity for consumables */}
      {item.item_type === 'consumable' && (
        <p className="text-yellow-400 text-sm text-center mb-3 font-medium">
          x{quantity}
        </p>
      )}

      {/* Action button */}
      {isCosmetic && (
        <div className="mt-3">
          {equipped ? (
            <NeonButton
              variant="secondary"
              size="sm"
              className="w-full"
              onClick={() => onUnequip(item.item_type)}
              disabled={isProcessing}
            >
              {isProcessing ? <Loader2 className="w-4 h-4 animate-spin" /> : 'Снять'}
            </NeonButton>
          ) : (
            <NeonButton
              size="sm"
              className="w-full"
              onClick={() => onEquip(inventoryItem.id)}
              disabled={isProcessing}
            >
              {isProcessing ? <Loader2 className="w-4 h-4 animate-spin" /> : 'Надеть'}
            </NeonButton>
          )}
        </div>
      )}

      {/* Consumable info */}
      {item.item_type === 'consumable' && (
        <p className="text-gray-500 text-xs text-center mt-2">
          Используйте в марафоне
        </p>
      )}
    </GlassCard>
  )
}

export function InventoryPage() {
  const { inventory, balance, isLoading, loadInventory, loadBalance, equip, unequip, clearError, error } = useShopStore()
  const toast = useToast()

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

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

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

  const handleEquip = async (inventoryId: number) => {
    setProcessingId(inventoryId)
    const success = await equip(inventoryId)
    setProcessingId(null)

    if (success) {
      toast.success('Предмет экипирован!')
    }
  }

  const handleUnequip = async (itemType: ShopItemType) => {
    setProcessingId(-1) // Generic processing state
    const success = await unequip(itemType)
    setProcessingId(null)

    if (success) {
      toast.success('Предмет снят')
    }
  }

  const filteredInventory = activeTab === 'all'
    ? inventory
    : inventory.filter(inv => inv.item.item_type === activeTab)

  // Group by type for display
  const cosmeticItems = filteredInventory.filter(inv => inv.item.item_type !== 'consumable')
  const consumableItems = filteredInventory.filter(inv => inv.item.item_type === 'consumable')

  const tabs: { id: ShopItemType | 'all'; label: string; icon: React.ReactNode }[] = [
    { id: 'all', label: 'Все', icon: <Package 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 && inventory.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">
            <Package 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 shop */}
          <Link to="/shop">
            <NeonButton>
              <ShoppingBag 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>

      {/* Empty state */}
      {filteredInventory.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 mb-4">
            {activeTab === 'all'
              ? 'Твой инвентарь пуст'
              : 'Нет предметов в этой категории'}
          </p>
          <Link to="/shop">
            <NeonButton>
              <ShoppingBag className="w-4 h-4 mr-2" />
              Перейти в магазин
            </NeonButton>
          </Link>
        </GlassCard>
      ) : (
        <>
          {/* Cosmetic items */}
          {cosmeticItems.length > 0 && (activeTab === 'all' || activeTab !== 'consumable') && (
            <div className="mb-8">
              {activeTab === 'all' && (
                <h2 className="text-xl font-semibold text-white mb-4">Косметика</h2>
              )}
              <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-4">
                {cosmeticItems.map(inv => (
                  <InventoryItemCard
                    key={inv.id}
                    inventoryItem={inv}
                    onEquip={handleEquip}
                    onUnequip={handleUnequip}
                    isProcessing={processingId === inv.id || processingId === -1}
                  />
                ))}
              </div>
            </div>
          )}

          {/* Consumable items */}
          {consumableItems.length > 0 && (activeTab === 'all' || activeTab === 'consumable') && (
            <div>
              {activeTab === 'all' && (
                <h2 className="text-xl font-semibold text-white mb-4">Расходуемые</h2>
              )}
              <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-4">
                {consumableItems.map(inv => (
                  <InventoryItemCard
                    key={inv.id}
                    inventoryItem={inv}
                    onEquip={handleEquip}
                    onUnequip={handleUnequip}
                    isProcessing={false}
                  />
                ))}
              </div>
            </div>
          )}
        </>
      )}
    </div>
  )
}
