import { useRef } from 'react'
import { useStore } from '../store'
import { toast } from '../toast'

export default function PropertyPanel(): React.JSX.Element {
  const page = useStore((s) => s.pages[s.curIdx])
  const updatePage = useStore((s) => s.updatePage)
  const screens = useStore((s) => s.screens)
  const pages = useStore((s) => s.pages)
  // 屏幕下拉覆盖：物理屏幕数、最少 4 个、页面数量、页面中已使用的最大屏幕编号
  const screenCount = Math.max(screens.length, 4, pages.length, ...pages.map((p) => p.screen))

  /** 最近一次已提取的 URL，避免重复提取 */
  const lastMetaUrl = useRef('')

  if (!page) {
    return (
      <div className="panel edit-props">
        <div className="panel-head">
          <span className="ph-icon">⚙️</span>页面属性
        </div>
        <div className="panel-body">
          <div className="empty-hint">请选择页面</div>
        </div>
      </div>
    )
  }

  const setCtr = (v: string): void => {
    const n = parseInt(v, 10)
    if (isNaN(n) || n < 0 || n > 9) {
      toast('控制器编号范围 0-9', 'warn')
      return
    }
    updatePage({ ctrl: n })
  }

  /** 粘贴 http(s) URL 后提取网页标题与描述并自动填入属性 */
  const fillMetaFromUrl = async (url: string): Promise<void> => {
    const u = url.trim()
    if (!/^https?:\/\//i.test(u)) return
    if (lastMetaUrl.current === u) return
    lastMetaUrl.current = u
    toast('正在提取网页标题与描述…', 'info')
    try {
      const meta = await window.api.page.fetchMeta(u)
      if (!meta || (!meta.title && !meta.desc)) {
        toast('未提取到网页标题/描述，请确认 URL 可访问', 'warn')
        return
      }
      const patch: { title?: string; desc?: string } = {}
      if (meta.title) patch.title = meta.title
      if (meta.desc) patch.desc = meta.desc
      updatePage(patch)
      toast(patch.desc ? '已自动填入网页标题与描述' : '已自动填入网页标题', 'ok')
    } catch {
      toast('网页标题提取失败', 'warn')
    }
  }

  return (
    <div className="panel edit-props">
      <div className="panel-head">
        <span className="ph-icon">⚙️</span>页面属性
        <span style={{ marginLeft: 'auto', fontSize: 11, color: 'var(--c-text-faint)' }}>{page.id}</span>
      </div>
      <div className="panel-body">
        <div className="prop-grid">
          <div className="prop-section">基本信息</div>
          <div className="prop-item">
            <label>页面标题</label>
            <input type="text" value={page.title} onChange={(e) => updatePage({ title: e.target.value })} />
          </div>
          <div className="prop-item">
            <label>页面描述</label>
            <input type="text" value={page.desc} onChange={(e) => updatePage({ desc: e.target.value })} />
          </div>

          <div className="prop-section">发布调度</div>
          <div className="prop-item">
            <label>所属屏幕（ScreenIndex）</label>
            <select value={page.screen} onChange={(e) => updatePage({ screen: parseInt(e.target.value, 10) })}>
              {Array.from({ length: Math.max(screenCount, 1) }, (_, i) => i + 1).map((n) => (
                <option key={n} value={n}>
                  屏幕 {n}
                </option>
              ))}
            </select>
            <span className="hint">多屏发布时该页面将分发到此屏幕</span>
          </div>
          <div className="prop-item">
            <label>控制器编号（ControllerIndex）</label>
            <input
              type="number"
              min={0}
              max={9}
              value={page.ctrl}
              onChange={(e) => setCtr(e.target.value)}
            />
            <span className="hint">按数字键 1-9 可切换到对应控制器编号的页面</span>
          </div>
          <div className="prop-item">
            <label className="check-row">
              <input
                type="checkbox"
                checked={page.display}
                onChange={(e) => updatePage({ display: e.target.checked })}
              />
              参与多屏发布（IsDisplay）
            </label>
          </div>

          <div className="prop-section">页面内容</div>
          <div className="prop-item">
            <label>大屏页面 URL（PageUrl）</label>
            <textarea
              className="url-area"
              rows={5}
              value={page.url}
              onChange={(e) => updatePage({ url: e.target.value })}
              onPaste={(e) => {
                const pasted = e.clipboardData.getData('text').trim()
                if (/^https?:\/\//i.test(pasted)) void fillMetaFromUrl(pasted)
              }}
              placeholder={'sample-screen.html\nhttps://…\nabout:blank'}
            />
            <span className="hint">支持多行文本，相对路径基于应用运行目录解析；粘贴 http(s) 网址后自动提取网页标题与描述</span>
          </div>
          <div className="prop-item">
            <label>页面参数（PageParams，每行 key=value，最多 255 字符）</label>
            <textarea
              rows={4}
              maxLength={255}
              value={page.params}
              onChange={(e) => updatePage({ params: e.target.value })}
            />
            <span className="hint">已输入 {page.params.length} / 255</span>
          </div>
        </div>
      </div>
    </div>
  )
}
