import { useState } from 'react'
import { Zap, Users, Shield, Gift, ArrowLeftRight, Gamepad2, Play, Square } from 'lucide-react'
import { Button } from '@/components/ui'
import { eventsApi } from '@/api'
import type { ActiveEvent, EventType, Challenge } from '@/types'
import { EVENT_INFO } from '@/types'

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-4 h-4" />,
  common_enemy: <Users className="w-4 h-4" />,
  double_risk: <Shield className="w-4 h-4" />,
  jackpot: <Gift className="w-4 h-4" />,
  swap: <ArrowLeftRight className="w-4 h-4" />,
  game_choice: <Gamepad2 className="w-4 h-4" />,
}

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

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

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

  const handleStop = async () => {
    if (!confirm('Остановить событие досрочно?')) return

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

  if (activeEvent.event) {
    return (
      <div className="p-4 bg-gray-800 rounded-xl">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-2">
            {EVENT_ICONS[activeEvent.event.type]}
            <span className="font-medium">
              Активно: {EVENT_INFO[activeEvent.event.type].name}
            </span>
          </div>
          <Button
            variant="danger"
            size="sm"
            onClick={handleStop}
            isLoading={isStopping}
          >
            <Square className="w-4 h-4 mr-1" />
            Остановить
          </Button>
        </div>
      </div>
    )
  }

  return (
    <div className="p-4 bg-gray-800 rounded-xl space-y-4">
      <h3 className="font-bold text-white">Запустить событие</h3>

      <div className="grid grid-cols-2 sm:grid-cols-3 gap-2">
        {EVENT_TYPES.map((type) => (
          <button
            key={type}
            onClick={() => setSelectedType(type)}
            className={`
              p-3 rounded-lg border-2 transition-all text-left
              ${selectedType === type
                ? 'border-primary-500 bg-primary-500/10'
                : 'border-gray-700 hover:border-gray-600'}
            `}
          >
            <div className="flex items-center gap-2 mb-1">
              {EVENT_ICONS[type]}
              <span className="font-medium text-sm">{EVENT_INFO[type].name}</span>
            </div>
            <p className="text-xs text-gray-400 line-clamp-2">
              {EVENT_INFO[type].description}
            </p>
          </button>
        ))}
      </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="w-full p-2 bg-gray-700 border border-gray-600 rounded-lg text-white"
          >
            <option value="">— Выберите челлендж —</option>
            {challenges.map((c) => (
              <option key={c.id} value={c.id}>
                {c.game.title}: {c.title} ({c.points} очков)
              </option>
            ))}
          </select>
        </div>
      )}

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