import { useState } from 'react'
import { Zap, Users, Shield, Gift, ArrowLeftRight, Gamepad2, Play, Square, Sparkles } from 'lucide-react'
import { NeonButton } from '@/components/ui'
import { eventsApi } from '@/api'
import type { ActiveEvent, EventType, Challenge } from '@/types'
import { EVENT_INFO } from '@/types'
import { useToast } from '@/store/toast'
import { useConfirm } from '@/store/confirm'

interface EventControlProps {
  marathonId: number
  activeEvent: ActiveEvent
  challenges?: Challenge[]
  onEventChange: () => void
}

const EVENT_TYPES: EventType[] = [
  'golden_hour',
  'double_risk',
  'jackpot',
  'swap',
  'game_choice',
  'common_enemy',
]

const EVENT_ICONS: Record<EventType, React.ReactNode> = {
  golden_hour: <Zap className="w-5 h-5" />,
  common_enemy: <Users className="w-5 h-5" />,
  double_risk: <Shield className="w-5 h-5" />,
  jackpot: <Gift className="w-5 h-5" />,
  swap: <ArrowLeftRight className="w-5 h-5" />,
  game_choice: <Gamepad2 className="w-5 h-5" />,
}

const EVENT_COLORS: Record<EventType, { selected: string; icon: string }> = {
  golden_hour: { selected: 'border-yellow-500/50 bg-yellow-500/10', icon: 'text-yellow-400' },
  common_enemy: { selected: 'border-red-500/50 bg-red-500/10', icon: 'text-red-400' },
  double_risk: { selected: 'border-purple-500/50 bg-purple-500/10', icon: 'text-purple-400' },
  jackpot: { selected: 'border-green-500/50 bg-green-500/10', icon: 'text-green-400' },
  swap: { selected: 'border-neon-500/50 bg-neon-500/10', icon: 'text-neon-400' },
  game_choice: { selected: 'border-orange-500/50 bg-orange-500/10', icon: 'text-orange-400' },
}

// Default durations for events (in minutes)
const DEFAULT_DURATIONS: Record<EventType, number | null> = {
  golden_hour: 45,
  common_enemy: null, // Until all complete
  double_risk: 120,
  jackpot: null, // 1 spin
  swap: 60,
  game_choice: 120,
}

export function EventControl({
  marathonId,
  activeEvent,
  challenges,
  onEventChange,
}: EventControlProps) {
  const toast = useToast()
  const confirm = useConfirm()
  const [selectedType, setSelectedType] = useState<EventType>('golden_hour')
  const [selectedChallengeId, setSelectedChallengeId] = useState<number | null>(null)
  const [durationMinutes, setDurationMinutes] = useState<number | ''>(45)
  const [isStarting, setIsStarting] = useState(false)
  const [isStopping, setIsStopping] = useState(false)

  // Update duration when event type changes
  const handleTypeChange = (type: EventType) => {
    setSelectedType(type)
    const defaultDuration = DEFAULT_DURATIONS[type]
    setDurationMinutes(defaultDuration ?? '')
  }

  const handleStart = async () => {
    if (selectedType === 'common_enemy' && !selectedChallengeId) {
      toast.warning('Выберите челлендж для события "Общий враг"')
      return
    }

    setIsStarting(true)
    try {
      await eventsApi.start(marathonId, {
        type: selectedType,
        duration_minutes: durationMinutes || undefined,
        challenge_id: selectedType === 'common_enemy' ? selectedChallengeId ?? undefined : undefined,
      })
      onEventChange()
    } catch (error) {
      console.error('Failed to start event:', error)
      toast.error('Не удалось запустить событие')
    } finally {
      setIsStarting(false)
    }
  }

  const handleStop = async () => {
    const confirmed = await confirm({
      title: 'Остановить событие?',
      message: 'Событие будет завершено досрочно.',
      confirmText: 'Остановить',
      cancelText: 'Отмена',
      variant: 'warning',
    })
    if (!confirmed) return

    setIsStopping(true)
    try {
      await eventsApi.stop(marathonId)
      onEventChange()
    } catch (error) {
      console.error('Failed to stop event:', error)
    } finally {
      setIsStopping(false)
    }
  }

  if (activeEvent.event) {
    const colors = EVENT_COLORS[activeEvent.event.type]
    return (
      <div className={`glass rounded-xl p-4 border ${colors.selected}`}>
        <div className="flex items-center justify-between gap-4 flex-wrap">
          <div className="flex items-center gap-3">
            <div className={`p-2 rounded-lg bg-white/10 ${colors.icon}`}>
              {EVENT_ICONS[activeEvent.event.type]}
            </div>
            <div>
              <span className="font-semibold text-white">
                {EVENT_INFO[activeEvent.event.type].name}
              </span>
              <span className="text-gray-400 text-sm ml-2">активно</span>
            </div>
          </div>
          <NeonButton
            variant="outline"
            size="sm"
            onClick={handleStop}
            isLoading={isStopping}
            className="border-red-500/50 text-red-400 hover:bg-red-500/10"
            icon={<Square className="w-4 h-4" />}
          >
            Остановить
          </NeonButton>
        </div>
      </div>
    )
  }

  return (
    <div className="glass rounded-xl p-5 space-y-5">
      <div className="flex items-center gap-3">
        <div className="w-10 h-10 rounded-xl bg-accent-500/20 flex items-center justify-center">
          <Sparkles className="w-5 h-5 text-accent-400" />
        </div>
        <div>
          <h3 className="font-semibold text-white">Запустить событие</h3>
          <p className="text-sm text-gray-400">Выберите тип и настройте параметры</p>
        </div>
      </div>

      <div className="grid grid-cols-2 sm:grid-cols-3 gap-3">
        {EVENT_TYPES.map((type) => {
          const colors = EVENT_COLORS[type]
          const isSelected = selectedType === type
          return (
            <button
              key={type}
              onClick={() => handleTypeChange(type)}
              className={`
                relative p-4 rounded-xl border-2 transition-all duration-300 text-left
                ${isSelected
                  ? `${colors.selected} shadow-lg`
                  : 'border-dark-600 bg-dark-700/50 hover:border-dark-500'
                }
              `}
            >
              <div className={`flex items-center gap-2 mb-2 ${isSelected ? colors.icon : 'text-gray-400'}`}>
                {EVENT_ICONS[type]}
                <span className={`font-semibold text-sm ${isSelected ? 'text-white' : 'text-gray-300'}`}>
                  {EVENT_INFO[type].name}
                </span>
              </div>
              <p className="text-xs text-gray-500 line-clamp-2">
                {EVENT_INFO[type].description}
              </p>
              {isSelected && (
                <div className="absolute top-2 right-2">
                  <div className={`w-2 h-2 rounded-full ${colors.icon.replace('text-', 'bg-')} animate-pulse`} />
                </div>
              )}
            </button>
          )
        })}
      </div>

      {/* Duration setting */}
      {DEFAULT_DURATIONS[selectedType] !== null && (
        <div>
          <label className="block text-sm font-medium text-gray-300 mb-2">
            Длительность (минуты)
          </label>
          <input
            type="number"
            value={durationMinutes}
            onChange={(e) => setDurationMinutes(e.target.value ? parseInt(e.target.value) : '')}
            min={1}
            max={480}
            placeholder={`По умолчанию: ${DEFAULT_DURATIONS[selectedType]}`}
            className="input w-full"
          />
          <p className="text-xs text-gray-500 mt-1.5">
            Оставьте пустым для значения по умолчанию ({DEFAULT_DURATIONS[selectedType]} мин)
          </p>
        </div>
      )}

      {selectedType === 'common_enemy' && challenges && challenges.length > 0 && (
        <div>
          <label className="block text-sm font-medium text-gray-300 mb-2">
            Выберите челлендж для всех
          </label>
          <select
            value={selectedChallengeId || ''}
            onChange={(e) => setSelectedChallengeId(e.target.value ? Number(e.target.value) : null)}
            className="input w-full"
          >
            <option value="">— Выберите челлендж —</option>
            {challenges.map((c) => (
              <option key={c.id} value={c.id}>
                {c.game.title}: {c.title} ({c.points} очков)
              </option>
            ))}
          </select>
        </div>
      )}

      <NeonButton
        onClick={handleStart}
        isLoading={isStarting}
        disabled={selectedType === 'common_enemy' && !selectedChallengeId}
        className="w-full"
        icon={<Play className="w-4 h-4" />}
      >
        Запустить {EVENT_INFO[selectedType].name}
      </NeonButton>
    </div>
  )
}
