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

const LOCK_KEYS = ['F9', 'F8', 'F10', 'ScrollLock', 'Pause', 'NumLock']

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

  const [threshold, setThreshold] = useState(settings?.keyThreshold ?? 350)
  const [lockKey, setLockKey] = useState(settings?.keyLockKey ?? 'F9')
  const [locked, setLocked] = useState(false)
  const [log, setLog] = useState<{ key: string; code: string; t: string }[]>([])

  // 设置异步加载完成后同步一次
  const synced = useRef(false)
  useEffect(() => {
    if (settings && !synced.current) {
      synced.current = true
      setThreshold(settings.keyThreshold)
      setLockKey(settings.keyLockKey)
    }
  }, [settings])

  useEffect(() => {
    void window.api.screens.keyLockState().then(setLocked)
  }, [])

  const goCtrl = (n: number): void => {
    const i = pages.findIndex((p) => p.ctrl === n)
    if (i >= 0) {
      st().selectPage(i)
      st().setView('edit')
      toast(`已切换到 控制器 ${n}：${pages[i].title}`, 'ok')
    } else {
      toast(`没有 控制器 ${n} 对应的页面`, 'warn')
    }
  }
  const goRel = (d: number): void => {
    const i = Math.max(0, Math.min(st().curIdx + d, pages.length - 1))
    st().selectPage(i)
    st().setView('edit')
  }
  const toggleLock = async (): Promise<void> => {
    const nv = !locked
    setLocked(nv)
    await window.api.screens.keyLock(nv)
    toast(
      nv ? `已锁定快捷键识别（按 ${lockKey} 解锁），网页内输入数字不会切屏` : '已解锁，数字/方向键识别恢复',
      nv ? 'info' : 'ok'
    )
  }
  const save = async (): Promise<void> => {
    await st().updateSettings({ keyThreshold: threshold, keyLockKey: lockKey })
    toast('遥控设置已保存', 'ok')
  }

  return (
    <div className="cfg-section">
      <div className="cfg-card">
        <div className="cfg-card-head">遥控器模拟器</div>
        <div className="cfg-card-body rc-body">
          <div className="rc-remote">
            <div className="rc-name">智慧农业 · 遥控器</div>
            <div className="rc-grid">
              {[1, 2, 3, 4, 5, 6, 7, 8, 9].map((n) => (
                <button key={n} className="rc-btn num" onClick={() => goCtrl(n)}>
                  {n}
                </button>
              ))}
            </div>
            <div className="rc-rows">
              <button className="rc-btn nav" onClick={() => goRel(-1)} title="切换到上一页">
                ↑
              </button>
              <button className="rc-btn nav" onClick={() => goRel(1)} title="切换到下一页">
                ↓
              </button>
              <button className="rc-btn esc" onClick={() => void closeAllScreenOutput()} title="关闭所有播放页面">
                Esc
              </button>
              <button
                className={'rc-btn lock' + (locked ? ' on' : '')}
                onClick={() => void toggleLock()}
                title={`${lockKey}：锁定/解锁快捷键识别`}
              >
                {locked ? '🔒' : '🔓'}
              </button>
            </div>
            <div className="rc-state">
              快捷键识别：<b className={locked ? 'txt-red' : 'txt-green'}>{locked ? '已锁定' : '正常'}</b>
            </div>
          </div>

          <div className="rc-side">
            <div className="cfg-field">
              <label>快捷键触发阈值</label>
              <div className="cfg-range">
                <input
                  type="range"
                  min={100}
                  max={1500}
                  step={50}
                  value={threshold}
                  onChange={(e) => setThreshold(Number(e.target.value))}
                />
                <span className="cfg-range-val">{threshold} ms</span>
              </div>
            </div>
            <div className="cfg-field">
              <label>锁定/解锁快捷键</label>
              <select className="cfg-input" value={lockKey} onChange={(e) => setLockKey(e.target.value)}>
                {LOCK_KEYS.map((k) => (
                  <option key={k} value={k}>
                    {k}
                  </option>
                ))}
              </select>
            </div>
            <p className="cfg-tip">
              避坑说明：大屏网页内交互输入数字也会触发"切屏"快捷键。设置阈值后，数字/方向键需
              <b> 长按超过阈值 </b>才会切屏，快速输入不受影响；演示时可按 <b>{lockKey}</b> 一键锁定/解锁快捷键识别。
            </p>
            <div className="pub-actions">
              <button className="btn primary" onClick={() => void save()}>
                💾 保存设置
              </button>
            </div>
          </div>
        </div>
      </div>

      <div className="cfg-card">
        <div className="cfg-card-head">快捷键测试区</div>
        <div className="cfg-card-body">
          <p className="cfg-tip">
            在下方输入框内敲击按键可测试真实键盘行为：快速按数字键 1-9 会正常输入，不会触发切屏；<b>长按</b>数字键超过阈值才会触发切屏。
          </p>
          <textarea
            className="cfg-input rc-test"
            placeholder="在此输入测试，如快速按 123456789 或 长按数字键"
            onKeyDown={(e) => {
              setLog((l) => [
                { key: e.key, code: e.code, t: new Date().toLocaleTimeString('zh-CN', { hour12: false }) },
                ...l
              ].slice(0, 8))
            }}
          />
          <div className="rc-log">
            {log.length === 0 && <span className="cfg-tip">按键记录将显示在这里</span>}
            {log.map((k, i) => (
              <span key={i} className="rc-log-item">
                <b>{k.key}</b> <i>{k.code}</i> {k.t}
              </span>
            ))}
          </div>
        </div>
      </div>

      <div className="cfg-card">
        <div className="cfg-card-head">快捷键速查</div>
        <div className="cfg-card-body">
          <table className="cfg-table">
            <thead>
              <tr>
                <th>按键</th>
                <th>功能</th>
                <th>位置</th>
              </tr>
            </thead>
            <tbody>
              <tr><td>1-9</td><td>进入对应控制器编号的页面</td><td>大屏 / 主窗口 / 轮播</td></tr>
              <tr><td>↑ ↓（或 ← →）</td><td>轮播页面上/下切换</td><td>单屏轮播</td></tr>
              <tr><td>Esc</td><td>退出全屏 / 关闭播放</td><td>大屏 / 轮播 / 主窗口</td></tr>
              <tr><td>F5</td><td>刷新当前页面</td><td>大屏 / 轮播 / 主窗口</td></tr>
              <tr><td>{lockKey}</td><td>锁定 / 解锁快捷键识别</td><td>大屏 / 轮播 / 主窗口</td></tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  )
}
