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

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

  const [name, setName] = useState(settings?.projectName ?? '')
  const [ver, setVer] = useState(settings?.projectVersion ?? '')
  const [pwd, setPwd] = useState(settings?.jsonPassword ?? '')
  const [showPwd, setShowPwd] = useState(false)

  // 设置异步加载完成后同步一次
  const synced = useRef(false)
  useEffect(() => {
    if (settings && !synced.current) {
      synced.current = true
      setName(settings.projectName)
      setVer(settings.projectVersion)
      setPwd(settings.jsonPassword)
    }
  }, [settings])

  const save = async (): Promise<void> => {
    await st().updateSettings({ projectName: name.trim() || '智慧农业大数据可视化控制中心', projectVersion: ver.trim() || '0.1.0', jsonPassword: pwd })
    toast('项目信息与 JSON 密码已保存', 'ok')
  }

  return (
    <div className="cfg-section">
      <div className="cfg-card">
        <div className="cfg-card-head">项目信息</div>
        <div className="cfg-card-body">
          <div className="cfg-field">
            <label>项目名称</label>
            <input className="cfg-input" value={name} onChange={(e) => setName(e.target.value)} placeholder="例如：智慧农业大数据可视化控制中心" />
          </div>
          <div className="cfg-field">
            <label>版本号</label>
            <input className="cfg-input" value={ver} onChange={(e) => setVer(e.target.value)} placeholder="例如：0.1.0" />
          </div>
          <p className="cfg-tip">项目名称与版本号会写入工程 JSON（appName / version），并作为「另存为」时的默认文件名。</p>
        </div>
      </div>

      <div className="cfg-card">
        <div className="cfg-card-head">
          JSON 文件读写密码
          <span className="cfg-badge">可选</span>
        </div>
        <div className="cfg-card-body">
          <div className="cfg-field">
            <label>读写密码</label>
            <div className="cfg-pwd">
              <input
                className="cfg-input"
                type={showPwd ? 'text' : 'password'}
                value={pwd}
                onChange={(e) => setPwd(e.target.value)}
                placeholder="留空则不加密"
              />
              <button className="btn" onClick={() => setShowPwd(!showPwd)}>
                {showPwd ? '隐藏' : '显示'}
              </button>
            </div>
          </div>
          <p className="cfg-tip">
            设置后，保存工程时会对每个页面的 <b>URL</b> 和 <b>网页参数</b> 进行 AES-256-GCM
            加密，防止 JSON 文件泄露后明文暴露链接与参数；打开时需输入同一密码解密。密码错误将无法打开。
          </p>
        </div>
      </div>

      <div className="cfg-card">
        <div className="cfg-card-head">当前工程</div>
        <div className="cfg-card-body">
          <div className="cfg-row">
            <span className="cfg-row-label">工程路径</span>
            <span className="cfg-row-value" title={filePath ?? ''}>
              {filePath || '未保存（暂存于内存）'}
            </span>
          </div>
          <div className="cfg-row">
            <span className="cfg-row-label">页面数量</span>
            <span className="cfg-row-value">{pages.length}</span>
          </div>
          <div className="cfg-row">
            <span className="cfg-row-label">屏幕数量</span>
            <span className="cfg-row-value">{screens.length > 0 ? screens.length : '未检测'}</span>
          </div>
          <div className="pub-actions">
            <button className="btn primary" onClick={() => void save()}>
              💾 保存配置
            </button>
            <button className="btn" onClick={() => void st().open()}>
              📂 打开工程
            </button>
            <button className="btn" onClick={() => void st().save()}>
              💾 保存工程
            </button>
            <button className="btn" onClick={() => void st().saveAs()}>
              📤 另存为
            </button>
          </div>
        </div>
      </div>
    </div>
  )
}
