import { useEffect, useRef, useState } from 'react'
import Modal from './Modal'
import { answerPassword, usePwd } from '../passwordState'

export function PasswordModal(): React.JSX.Element | null {
  const open = usePwd((s) => s.open)
  const title = usePwd((s) => s.title)
  const [val, setVal] = useState('')
  const inputRef = useRef<HTMLInputElement>(null)

  useEffect(() => {
    if (open) {
      setVal('')
      const t = setTimeout(() => inputRef.current?.focus(), 40)
      return () => clearTimeout(t)
    }
    return undefined
  }, [open])

  if (!open) return null
  return (
    <Modal
      title={title}
      onClose={() => answerPassword(null)}
      width={420}
      footer={
        <>
          <button className="btn" onClick={() => answerPassword(null)}>
            取消
          </button>
          <button className="btn primary" disabled={!val} onClick={() => answerPassword(val)}>
            确定
          </button>
        </>
      }
    >
      <p className="m-hint">该工程文件已被密码保护，请输入 JSON 读写密码以解密（URL 与网页参数）。</p>
      <input
        ref={inputRef}
        type="password"
        className="cfg-input"
        value={val}
        placeholder="请输入密码"
        onChange={(e) => setVal(e.target.value)}
        onKeyDown={(e) => {
          if (e.key === 'Enter' && val) answerPassword(val)
        }}
      />
    </Modal>
  )
}
