import { useEffect, useState } from 'react'
import Modal from './Modal'
import { useStore } from '../store'
import type { ScreenInfo } from '../types'
import { publishCurrentToScreen, startCarouselOnScreen, publishAll, detectScreens } from '../publishActions'

/** 通用屏幕列表行 */
function ScreenRow({ s, selected, onSelect }: { s: ScreenInfo; selected: boolean; onSelect: () => void }): React.JSX.Element {
  return (
    <div className={'m-screen-row' + (selected ? ' sel' : '')} onClick={onSelect}>
      <div className="msr-main">
        <span className="msr-name">屏幕 {s.index}</span>
        {s.primary && <span className="msr-badge">主显示器</span>}
      </div>
      <div className="msr-sub">
        <span>
          {s.res} · {s.pos}
        </span>
        {s.playing ? (
          <span className="msr-playing">▶ {s.playing.title}</span>
        ) : (
          <span className="msr-idle">空闲</span>
        )}
      </div>
    </div>
  )
}

/** 选择屏幕后执行操作的弹窗（预览本页 / 单屏发布共用） */
export function ScreenSelectModal(props: {
  title: string
  hint: string
  confirmLabel: string
  /** 仅单屏发布：显示「自动轮播 + 间隔秒数」选项 */
  showCarousel?: boolean
  onConfirm: (index: number, opts: { carousel: boolean; intervalSec: number }) => void
  onClose: () => void
}): React.JSX.Element {
  const screens = useStore((s) => s.screens)
  const settings = useStore((s) => s.settings)
  const [sel, setSel] = useState<number>(screens[0]?.index ?? 0)
  const [carousel, setCarousel] = useState(props.showCarousel ?? false)
  const [intervalSec, setIntervalSec] = useState(settings?.publish.intervalSec ?? 10)
  return (
    <Modal
      title={props.title}
      onClose={props.onClose}
      width={470}
      footer={
        <>
          <button className="btn" onClick={props.onClose}>
            取消
          </button>
          <button
            className="btn primary"
            disabled={!sel}
            onClick={() => props.onConfirm(sel, { carousel, intervalSec: Math.max(1, Math.round(intervalSec)) })}
          >
            {props.confirmLabel}
          </button>
        </>
      }
    >
      <p className="m-hint">{props.hint}</p>
      {screens.length === 0 ? (
        <div className="m-empty">未检测到屏幕，请先执行「检测屏幕」</div>
      ) : (
        <div className="m-screen-list">
          {screens.map((s) => (
            <ScreenRow key={s.index} s={s} selected={sel === s.index} onSelect={() => setSel(s.index)} />
          ))}
        </div>
      )}
      {props.showCarousel && (
        <div className="m-carousel">
          <label className="m-check">
            <input type="checkbox" checked={carousel} onChange={(e) => setCarousel(e.target.checked)} />
            <span>
              自动轮播所有「参与多屏发布」的页面
              <em>（不勾选则固定显示第一页，可用 ↑/↓ 手动切换）</em>
            </span>
          </label>
          {carousel && (
            <div className="m-interval">
              <span className="m-interval-label">轮播间隔</span>
              <input
                type="number"
                min={1}
                max={3600}
                value={intervalSec}
                onChange={(e) => setIntervalSec(Number(e.target.value))}
              />
              <span>秒</span>
            </div>
          )}
        </div>
      )}
    </Modal>
  )
}

/** 多屏发布弹窗：预览各屏幕布局与页面分配 + 编辑器屏幕全屏开关 */
export function MultiPublishModal(props: { onClose: () => void }): React.JSX.Element {
  const screens = useStore((s) => s.screens)
  const pages = useStore((s) => s.pages)
  const [alsoMain, setAlsoMain] = useState(false)
  const [mainIdx, setMainIdx] = useState(0)

  useEffect(() => {
    void window.api.screens.mainIndex().then((n) => setMainIdx(n))
  }, [])

  return (
    <Modal
      title="多屏发布"
      onClose={props.onClose}
      width={640}
      footer={
        <>
          <button className="btn" onClick={props.onClose}>
            取消
          </button>
          <button
            className="btn primary"
            onClick={() => {
              void publishAll(alsoMain)
              props.onClose()
            }}
          >
            确定发布
          </button>
        </>
      }
    >
      <p className="m-hint">
        各页面将按「所属屏幕 ID」分发到对应屏幕全屏播放（Esc 退出 · F5 刷新 · 数字键切页）。
      </p>
      {screens.length === 0 ? (
        <div className="m-empty">未检测到屏幕，请先执行「检测屏幕」</div>
      ) : (
        <div className="m-screen-grid">
          {screens.map((s) => {
            const list = pages.filter((p) => p.display && p.screen === s.index)
            return (
              <div key={s.index} className="m-scard">
                <div className="m-scard-head">
                  <span className="msr-name">屏幕 {s.index}</span>
                  {s.primary && <span className="msr-badge">主显示器</span>}
                  <span className="msr-res">{s.res}</span>
                </div>
                <div className="m-scard-pages">
                  {list.length === 0 ? (
                    <span className="m-page-empty">无匹配页面</span>
                  ) : (
                    list.slice(0, 3).map((p) => (
                      <span key={p.id} className="m-page-chip" title={p.title}>
                        {p.title}
                      </span>
                    ))
                  )}
                  {list.length > 3 && <span className="m-page-more">+{list.length - 3}</span>}
                </div>
                {s.playing && <div className="m-scard-play">正在播放：{s.playing.title}</div>}
              </div>
            )
          })}
        </div>
      )}
      <label className="m-check">
        <input type="checkbox" checked={alsoMain} onChange={(e) => setAlsoMain(e.target.checked)} />
        同时在本机编辑器屏幕上全屏显示页面（屏幕 {mainIdx || '—'}）
      </label>
    </Modal>
  )
}

/** 检测屏幕弹窗：显示已连接屏幕列表，各屏同时显示编号标签 */
export function DetectModal(props: { onClose: () => void }): React.JSX.Element {
  const screens = useStore((s) => s.screens)
  useEffect(() => {
    void detectScreens()
  }, [])
  return (
    <Modal
      title="检测屏幕"
      onClose={props.onClose}
      width={520}
      footer={
        <button className="btn primary" onClick={props.onClose}>
          知道了
        </button>
      }
    >
      <p className="m-hint">
        已在全部分屏左上角显示「编号 + 分辨率」标签（约 6 秒后自动关闭），便于确认屏幕布局。
      </p>
      <div className="m-screen-list">
        {screens.length === 0 ? (
          <div className="m-empty">未检测到屏幕</div>
        ) : (
          screens.map((s) => (
            <div key={s.index} className="m-screen-row">
              <div className="msr-main">
                <span className="msr-name">屏幕 {s.index}</span>
                {s.primary && <span className="msr-badge">主显示器</span>}
                <span className="msr-res">{s.res}</span>
              </div>
              <div className="msr-sub">
                <span>{s.pos}</span>
                {s.playing ? (
                  <span className="msr-playing">▶ {s.playing.title}</span>
                ) : (
                  <span className="msr-idle">空闲</span>
                )}
              </div>
            </div>
          ))
        )}
      </div>
    </Modal>
  )
}
