import { useEffect, useRef, useState } from 'react'
import { useStore } from '../../store'
import { toast } from '../../toast'
import { publishAll, applyPublishDefaults, startCarouselOnScreen } from '../../publishActions'

export default function PublishSettings(): React.JSX.Element {
  const settings = useStore((s) => s.settings)
  const screens = useStore((s) => s.screens)
  const st = useStore.getState

  const [mode, setMode] = useState<'multi' | 'single' | 'main'>(settings?.publish.mode ?? 'multi')
  const [screenIndex, setScreenIndex] = useState(settings?.publish.screenIndex ?? 1)
  const [alsoMain, setAlsoMain] = useState(settings?.publish.alsoMain ?? false)
  const [intervalSec, setIntervalSec] = useState(settings?.publish.intervalSec ?? 10)

  // 设置异步加载完成后同步一次
  const synced = useRef(false)
  useEffect(() => {
    if (settings && !synced.current) {
      synced.current = true
      setMode(settings.publish.mode)
      setScreenIndex(settings.publish.screenIndex)
      setAlsoMain(settings.publish.alsoMain)
      setIntervalSec(settings.publish.intervalSec)
    }
  }, [settings])

  const save = async (): Promise<void> => {
    await st().updateSettings({
      publish: { mode, screenIndex, alsoMain, intervalSec: Math.max(0, Math.round(intervalSec)) }
    })
    toast('发布默认值已保存', 'ok')
  }

  const testPublish = async (): Promise<void> => {
    await save()
    await applyPublishDefaults()
  }

  return (
    <div className="cfg-section">
      <p className="cfg-tip">
        这里是「打开项目并进入发布」快捷方式使用的默认发布配置，也可用于一键按默认方式发布当前工程。
      </p>
      <div className="cfg-card">
        <div className="cfg-card-head">发布方式</div>
        <div className="cfg-card-body">
          <label className="cfg-radio">
            <input type="radio" checked={mode === 'multi'} onChange={() => setMode('multi')} />
            <b>多屏发布</b> —— 各页面按「所属屏幕 ID」分发到对应屏幕全屏播放
          </label>
          <label className="cfg-radio">
            <input type="radio" checked={mode === 'single'} onChange={() => setMode('single')} />
            <b>单屏发布</b> —— 在指定屏幕轮播所有「参与多屏发布」的页面
          </label>
          <label className="cfg-radio">
            <input type="radio" checked={mode === 'main'} onChange={() => setMode('main')} />
            <b>编辑器屏幕全屏</b> —— 在本机编辑器屏幕上全屏显示第一个页面
          </label>

          {mode === 'multi' && (
            <label className="cfg-check">
              <input type="checkbox" checked={alsoMain} onChange={(e) => setAlsoMain(e.target.checked)} />
              多屏发布时，同时在本机编辑器屏幕上全屏显示对应页面
            </label>
          )}

          {mode === 'single' && (
            <div className="cfg-field">
              <label>目标屏幕</label>
              <select className="cfg-input" value={screenIndex} onChange={(e) => setScreenIndex(Number(e.target.value))}>
                {screens.length === 0 && <option value={1}>屏幕 1（未检测）</option>}
                {screens.map((s) => (
                  <option key={s.index} value={s.index}>
                    屏幕 {s.index}
                    {s.primary ? '（主显示器）' : ''} {s.res}
                  </option>
                ))}
              </select>
            </div>
          )}

          {mode === 'single' && (
            <div className="cfg-field">
              <label>自动切换间隔（秒，0 = 不自动切换）</label>
              <input
                type="number"
                className="cfg-input"
                min={0}
                max={3600}
                value={intervalSec}
                onChange={(e) => setIntervalSec(Number(e.target.value))}
              />
            </div>
          )}
        </div>
      </div>

      <div className="cfg-card">
        <div className="cfg-card-head">操作</div>
        <div className="cfg-card-body">
          <div className="pub-actions">
            <button className="btn primary" onClick={() => void save()}>
              💾 保存发布设置
            </button>
            <button className="btn" onClick={() => void testPublish()}>
              ▶ 按默认配置发布当前工程
            </button>
            {mode === 'single' && (
              <button className="btn" onClick={() => void startCarouselOnScreen(screenIndex, intervalSec)}>
                🎠 立即单屏发布
              </button>
            )}
            {mode === 'multi' && (
              <button className="btn" onClick={() => void publishAll(alsoMain)}>
                🖥️ 立即多屏发布
              </button>
            )}
          </div>
        </div>
      </div>
    </div>
  )
}
