import { useState, useEffect } from 'react'
import { useParams, useNavigate } from 'react-router-dom'
import { shopApi, adminApi } from '@/api'
import { useToast } from '@/store/toast'
import { GlassCard, NeonButton, FramePreview } from '@/components/ui'
import {
  Loader2, Gift, ArrowLeft, Package,
  Frame, Type, Palette, Image, Zap, SkipForward,
  Minus, Plus, Shuffle, Dice5, Copy, Undo2, X, XCircle
} from 'lucide-react'
import type { ShopItem, ShopItemType, ShopItemPublic, AdminUser } 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" />,
  skip_exile: <XCircle 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" />,
}

const ITEM_TYPE_LABELS: Record<ShopItemType | 'all', string> = {
  all: 'Все',
  consumable: 'Расходники',
  frame: 'Рамки',
  title: 'Титулы',
  name_color: 'Цвета',
  background: 'Фоны',
}

interface GrantItemCardProps {
  item: ShopItem
  onGrant: (item: ShopItem) => void
}

function GrantItemCard({ item, onGrant }: GrantItemCardProps) {
  const rarityColors = RARITY_COLORS[item.rarity]

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

    if (item.item_type === 'name_color') {
      const data = item.asset_data as { style?: string; color?: string; gradient?: 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 }}
        />
      )
    }

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

      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(', ')})` }
      }

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

    if (item.item_type === 'frame') {
      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 hover:scale-[1.02]',
        rarityColors.border
      )}
    >
      {/* 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>

      {/* Grant button */}
      <NeonButton
        size="sm"
        color="neon"
        onClick={() => onGrant(item)}
        className="w-full"
        icon={<Gift className="w-4 h-4" />}
      >
        Выдать
      </NeonButton>
    </GlassCard>
  )
}

export function AdminGrantItemPage() {
  const { userId } = useParams<{ userId: string }>()
  const navigate = useNavigate()
  const toast = useToast()

  const [user, setUser] = useState<AdminUser | null>(null)
  const [items, setItems] = useState<ShopItem[]>([])
  const [isLoading, setIsLoading] = useState(true)
  const [activeTab, setActiveTab] = useState<ShopItemType | 'all'>('all')

  // Grant modal
  const [grantItem, setGrantItem] = useState<ShopItem | null>(null)
  const [grantQuantity, setGrantQuantity] = useState(1)
  const [grantReason, setGrantReason] = useState('')
  const [isGranting, setIsGranting] = useState(false)

  useEffect(() => {
    loadData()
  }, [userId])

  const loadData = async () => {
    if (!userId) return
    setIsLoading(true)
    try {
      const [userData, itemsData] = await Promise.all([
        adminApi.getUser(parseInt(userId)),
        shopApi.getItems(),
      ])
      setUser(userData)
      setItems(itemsData)
    } catch (err) {
      console.error('Failed to load data:', err)
      toast.error('Ошибка загрузки данных')
    } finally {
      setIsLoading(false)
    }
  }

  const handleGrant = async () => {
    if (!grantItem || !userId || !grantReason.trim()) return

    setIsGranting(true)
    try {
      await shopApi.adminGrantItem(
        parseInt(userId),
        grantItem.id,
        grantQuantity,
        grantReason
      )
      toast.success(`Выдано ${grantItem.name} x${grantQuantity} для ${user?.nickname}`)
      setGrantItem(null)
      setGrantQuantity(1)
      setGrantReason('')
    } catch (err: unknown) {
      const error = err as { response?: { data?: { detail?: string } } }
      toast.error(error.response?.data?.detail || 'Ошибка выдачи предмета')
    } finally {
      setIsGranting(false)
    }
  }

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

  if (isLoading) {
    return (
      <div className="flex flex-col items-center justify-center py-24">
        <Loader2 className="w-12 h-12 animate-spin text-neon-500 mb-4" />
        <p className="text-gray-400">Загрузка...</p>
      </div>
    )
  }

  if (!user) {
    return (
      <div className="text-center py-24">
        <p className="text-gray-400">Пользователь не найден</p>
      </div>
    )
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center gap-4">
        <button
          onClick={() => navigate('/admin/users')}
          className="w-10 h-10 rounded-xl bg-dark-700 border border-dark-600 flex items-center justify-center text-gray-400 hover:text-white hover:border-neon-500/30 transition-all"
        >
          <ArrowLeft className="w-5 h-5" />
        </button>
        <div>
          <h1 className="text-2xl font-bold text-white flex items-center gap-3">
            <Gift className="w-7 h-7 text-green-400" />
            Выдать предмет
          </h1>
          <p className="text-gray-400">
            Получатель: <span className="text-white font-medium">{user.nickname}</span>
          </p>
        </div>
      </div>

      {/* Tabs */}
      <div className="flex gap-2 flex-wrap">
        {(Object.keys(ITEM_TYPE_LABELS) as (ShopItemType | 'all')[]).map((type) => (
          <button
            key={type}
            onClick={() => setActiveTab(type)}
            className={clsx(
              'px-4 py-2 rounded-xl text-sm font-medium transition-all',
              activeTab === type
                ? 'bg-neon-500/20 text-neon-400 border border-neon-500/30'
                : 'bg-dark-700/50 text-gray-400 border border-dark-600 hover:text-white hover:border-dark-500'
            )}
          >
            {ITEM_TYPE_LABELS[type]}
          </button>
        ))}
      </div>

      {/* Items grid */}
      <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-4">
        {filteredItems.map(item => (
          <GrantItemCard
            key={item.id}
            item={item}
            onGrant={setGrantItem}
          />
        ))}
      </div>

      {filteredItems.length === 0 && (
        <div className="text-center py-12">
          <Package className="w-16 h-16 text-gray-600 mx-auto mb-4" />
          <p className="text-gray-400">Нет предметов в этой категории</p>
        </div>
      )}

      {/* Grant Modal */}
      {grantItem && (
        <div className="fixed inset-0 bg-black/60 backdrop-blur-sm flex items-center justify-center z-50">
          <div className="glass rounded-2xl p-6 max-w-md w-full mx-4 border border-dark-600 shadow-2xl">
            <div className="flex items-center justify-between mb-6">
              <h3 className="text-lg font-semibold text-white flex items-center gap-2">
                <Gift className="w-5 h-5 text-green-400" />
                Выдать {grantItem.name}
              </h3>
              <button
                onClick={() => {
                  setGrantItem(null)
                  setGrantQuantity(1)
                  setGrantReason('')
                }}
                className="p-1.5 text-gray-400 hover:text-white rounded-lg hover:bg-dark-600/50 transition-colors"
              >
                <X className="w-5 h-5" />
              </button>
            </div>

            <p className="text-gray-400 mb-4">
              Получатель: <span className="text-white">{user.nickname}</span>
            </p>

            {/* Quantity */}
            <div className="mb-4">
              <label className="block text-sm font-medium text-gray-300 mb-2">
                Количество
              </label>
              <div className="flex items-center gap-3">
                <button
                  onClick={() => setGrantQuantity(Math.max(1, grantQuantity - 1))}
                  disabled={grantQuantity <= 1}
                  className="w-10 h-10 rounded-xl 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-5 h-5" />
                </button>
                <input
                  type="number"
                  min="1"
                  max="100"
                  value={grantQuantity}
                  onChange={(e) => setGrantQuantity(Math.max(1, Math.min(100, parseInt(e.target.value) || 1)))}
                  className="w-20 text-center bg-dark-700/50 border border-dark-600 rounded-xl px-3 py-2 text-white font-bold text-lg focus:outline-none focus:border-neon-500/50"
                />
                <button
                  onClick={() => setGrantQuantity(Math.min(100, grantQuantity + 1))}
                  disabled={grantQuantity >= 100}
                  className="w-10 h-10 rounded-xl 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-5 h-5" />
                </button>
              </div>
            </div>

            {/* Reason */}
            <div className="mb-6">
              <label className="block text-sm font-medium text-gray-300 mb-2">
                Причина <span className="text-red-400">*</span>
              </label>
              <textarea
                value={grantReason}
                onChange={(e) => setGrantReason(e.target.value)}
                placeholder="Причина выдачи предмета..."
                rows={3}
                className="w-full bg-dark-700/50 border border-dark-600 rounded-xl px-4 py-2.5 text-white placeholder:text-gray-500 focus:outline-none focus:border-neon-500/50 transition-colors resize-none"
              />
            </div>

            <div className="flex gap-3 justify-end">
              <NeonButton
                variant="ghost"
                onClick={() => {
                  setGrantItem(null)
                  setGrantQuantity(1)
                  setGrantReason('')
                }}
              >
                Отмена
              </NeonButton>
              <NeonButton
                color="neon"
                onClick={handleGrant}
                disabled={!grantReason.trim() || isGranting}
                isLoading={isGranting}
                icon={<Gift className="w-4 h-4" />}
              >
                Выдать x{grantQuantity}
              </NeonButton>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
