import { useState, useEffect } from 'react'
import { widgetsApi } from '@/api/widgets'
import type { WidgetToken } from '@/types'
import { useToast } from '@/store/toast'

interface WidgetSettingsModalProps {
  marathonId: number
  isOpen: boolean
  onClose: () => void
}

type WidgetTheme = 'dark' | 'light' | 'neon'

type WidgetType = 'leaderboard' | 'current' | 'progress' | 'combined'

export function WidgetSettingsModal({ marathonId, isOpen, onClose }: WidgetSettingsModalProps) {
  const [token, setToken] = useState<WidgetToken | null>(null)
  const [loading, setLoading] = useState(false)
  const [theme, setTheme] = useState<WidgetTheme>('dark')
  const [count, setCount] = useState(5)
  const [showAvatars, setShowAvatars] = useState(true)
  const [transparent, setTransparent] = useState(false)
  const [previewType, setPreviewType] = useState<WidgetType>('leaderboard')
  const toast = useToast()

  useEffect(() => {
    if (isOpen && !token) {
      loadOrCreateToken()
    }
  }, [isOpen])

  const loadOrCreateToken = async () => {
    setLoading(true)
    try {
      const result = await widgetsApi.createToken(marathonId)
      setToken(result)
    } catch {
      toast.error('Не удалось создать токен')
    } finally {
      setLoading(false)
    }
  }

  const regenerateToken = async () => {
    if (!token) return
    setLoading(true)
    try {
      const result = await widgetsApi.regenerateToken(token.id)
      setToken(result)
      toast.success('Токен обновлён')
    } catch {
      toast.error('Не удалось обновить токен')
    } finally {
      setLoading(false)
    }
  }

  const buildWidgetUrl = (type: WidgetType) => {
    if (!token) return ''
    const baseUrl = window.location.origin
    const params = new URLSearchParams({
      marathon: marathonId.toString(),
      token: token.token,
      theme,
      ...(type === 'leaderboard' && { count: count.toString() }),
      ...(showAvatars === false && { avatars: 'false' }),
      ...(transparent && { transparent: 'true' }),
    })
    return `${baseUrl}/widget/${type}?${params}`
  }

  const copyToClipboard = (url: string, name: string) => {
    navigator.clipboard.writeText(url)
    toast.success(`Ссылка "${name}" скопирована`)
  }

  if (!isOpen) return null

  const widgetNames: Record<WidgetType, string> = {
    leaderboard: 'Лидерборд',
    current: 'Текущее задание',
    progress: 'Прогресс',
    combined: 'Всё в одном',
  }

  return (
    <div className="fixed inset-0 bg-black/60 flex items-center justify-center z-50 p-4">
      <div className="bg-dark-800 rounded-xl max-w-5xl w-full max-h-[90vh] overflow-y-auto">
        <div className="p-6 border-b border-dark-700">
          <div className="flex justify-between items-center">
            <h2 className="text-xl font-bold">Виджеты для OBS</h2>
            <button
              onClick={onClose}
              className="text-gray-400 hover:text-white transition-colors"
            >
              <svg className="w-6 h-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
              </svg>
            </button>
          </div>
        </div>

        <div className="p-6">
          {loading ? (
            <div className="text-center py-8">
              <div className="animate-spin w-8 h-8 border-2 border-primary border-t-transparent rounded-full mx-auto"></div>
              <p className="text-gray-400 mt-2">Загрузка...</p>
            </div>
          ) : token ? (
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
              {/* Left column - Preview */}
              <div className="space-y-4">
                <h3 className="font-semibold text-lg">Превью</h3>

                {/* Widget type tabs */}
                <div className="flex flex-wrap gap-2">
                  {(['leaderboard', 'current', 'progress', 'combined'] as WidgetType[]).map((type) => (
                    <button
                      key={type}
                      onClick={() => setPreviewType(type)}
                      className={`px-3 py-1.5 text-sm rounded-lg transition-colors ${
                        previewType === type
                          ? 'bg-primary text-white'
                          : 'bg-dark-700 text-gray-400 hover:text-white'
                      }`}
                    >
                      {widgetNames[type]}
                    </button>
                  ))}
                </div>

                {/* Preview iframe */}
                <div
                  className="rounded-lg overflow-hidden border border-dark-600"
                  style={{
                    background: transparent ? 'repeating-conic-gradient(#1a1a1a 0% 25%, #2a2a2a 0% 50%) 50% / 20px 20px'
                      : theme === 'light' ? '#f5f5f5' : '#121212'
                  }}
                >
                  <iframe
                    key={`${previewType}-${theme}-${count}-${showAvatars}-${transparent}`}
                    src={buildWidgetUrl(previewType)}
                    className="w-full"
                    style={{ height: '320px', border: 'none' }}
                    title="Widget Preview"
                  />
                </div>

                {/* Copy button for current preview */}
                <button
                  onClick={() => copyToClipboard(buildWidgetUrl(previewType), widgetNames[previewType])}
                  className="w-full px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/80 transition-colors"
                >
                  Копировать ссылку на {widgetNames[previewType]}
                </button>
              </div>

              {/* Right column - Settings */}
              <div className="space-y-6">
                {/* Settings */}
                <div className="space-y-4">
                  <h3 className="font-semibold text-lg">Настройки</h3>

                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <label className="block text-sm text-gray-400 mb-1">Тема</label>
                      <select
                        value={theme}
                        onChange={(e) => setTheme(e.target.value as WidgetTheme)}
                        className="w-full bg-dark-700 border border-dark-600 rounded-lg px-3 py-2"
                      >
                        <option value="dark">Тёмная</option>
                        <option value="light">Светлая</option>
                        <option value="neon">Неон</option>
                      </select>
                    </div>

                    <div>
                      <label className="block text-sm text-gray-400 mb-1">Участников в лидерборде</label>
                      <input
                        type="number"
                        min={1}
                        max={20}
                        value={count}
                        onChange={(e) => setCount(parseInt(e.target.value) || 5)}
                        className="w-full bg-dark-700 border border-dark-600 rounded-lg px-3 py-2"
                      />
                    </div>
                  </div>

                  <div className="flex gap-4">
                    <label className="flex items-center gap-2 cursor-pointer">
                      <input
                        type="checkbox"
                        checked={showAvatars}
                        onChange={(e) => setShowAvatars(e.target.checked)}
                        className="w-4 h-4 rounded"
                      />
                      <span className="text-sm">Показывать аватарки</span>
                    </label>

                    <label className="flex items-center gap-2 cursor-pointer">
                      <input
                        type="checkbox"
                        checked={transparent}
                        onChange={(e) => setTransparent(e.target.checked)}
                        className="w-4 h-4 rounded"
                      />
                      <span className="text-sm">Прозрачный фон</span>
                    </label>
                  </div>
                </div>

                {/* All Widget URLs */}
                <div className="space-y-3">
                  <h3 className="font-semibold text-lg">Все ссылки</h3>

                  {([
                    { type: 'leaderboard' as const, desc: 'Таблица участников' },
                    { type: 'current' as const, desc: 'Активное задание' },
                    { type: 'progress' as const, desc: 'Статистика' },
                    { type: 'combined' as const, desc: 'Всё в одном виджете' },
                  ]).map(({ type, desc }) => (
                    <div key={type} className="flex items-center justify-between bg-dark-700 rounded-lg px-4 py-3">
                      <div>
                        <div className="font-medium text-sm">{widgetNames[type]}</div>
                        <div className="text-xs text-gray-500">{desc}</div>
                      </div>
                      <button
                        onClick={() => copyToClipboard(buildWidgetUrl(type), widgetNames[type])}
                        className="px-3 py-1 bg-dark-600 text-white text-sm rounded-lg hover:bg-dark-500 transition-colors"
                      >
                        Копировать
                      </button>
                    </div>
                  ))}
                </div>

                {/* Instructions */}
                <div className="bg-dark-700/50 rounded-lg p-4">
                  <h4 className="font-medium mb-2 text-sm">Как добавить в OBS</h4>
                  <ol className="text-xs text-gray-400 space-y-1 list-decimal list-inside">
                    <li>Скопируйте нужную ссылку</li>
                    <li>В OBS: "+" → "Браузер"</li>
                    <li>Вставьте ссылку в поле URL</li>
                    <li>Размер: 400×300 px</li>
                  </ol>
                </div>

                {/* Token actions */}
                <div className="flex justify-between items-center pt-4 border-t border-dark-700">
                  <div className="text-xs text-gray-500">
                    Токен: {token.token.substring(0, 16)}...
                  </div>
                  <button
                    onClick={regenerateToken}
                    className="text-xs text-red-400 hover:text-red-300"
                  >
                    Сбросить токен
                  </button>
                </div>
              </div>
            </div>
          ) : (
            <div className="text-center py-8 text-gray-400">
              Не удалось загрузить данные
            </div>
          )}
        </div>
      </div>
    </div>
  )
}
