import { useEffect, useState, useCallback } from 'react'
import { api } from '../api/client.js'

const empty = {
  name: '',
  email: '',
  password: '',
  smtp_host: '',
  smtp_port: 465,
  imap_host: '',
  imap_port: 993,
  use_tls: true,
}

export default function Accounts() {
  const [list, setList] = useState([])
  const [form, setForm] = useState(empty)
  const [editing, setEditing] = useState(null)
  const [modalOpen, setModalOpen] = useState(false)
  const [err, setErr] = useState('')
  const [msg, setMsg] = useState('')

  const reload = () =>
    api
      .listAccounts()
      .then((rows) => setList(Array.isArray(rows) ? rows : []))
      .catch((e) => setErr(e.message))

  useEffect(() => {
    reload()
  }, [])

  const openNew = () => {
    setEditing(null)
    setForm(empty)
    setErr('')
    setMsg('')
    setModalOpen(true)
  }

  const openEdit = (a) => {
    setEditing(a.id)
    setForm({ ...a, password: '' })
    setErr('')
    setMsg('')
    setModalOpen(true)
  }

  const closeModal = useCallback(() => {
    setModalOpen(false)
    setEditing(null)
    setForm(empty)
    setErr('')
  }, [])

  useEffect(() => {
    if (!modalOpen) return
    const onKey = (e) => {
      if (e.key === 'Escape') closeModal()
    }
    window.addEventListener('keydown', onKey)
    return () => window.removeEventListener('keydown', onKey)
  }, [modalOpen, closeModal])

  const save = async (e) => {
    e.preventDefault()
    setErr('')
    try {
      if (editing) {
        await api.updateAccount(editing, form)
        setMsg('已更新')
      } else {
        await api.createAccount(form)
        setMsg('已创建')
      }
      closeModal()
      reload()
    } catch (e) {
      setErr(e.message)
    }
  }

  const del = async (id) => {
    if (!confirm('确定删除该账户?')) return
    try {
      await api.deleteAccount(id)
      setMsg('已删除')
      reload()
    } catch (e) {
      setErr(e.message)
    }
  }

  const set = (k) => (e) => {
    const v =
      e.target.type === 'checkbox'
        ? e.target.checked
        : e.target.type === 'number'
          ? Number(e.target.value)
          : e.target.value
    setForm({ ...form, [k]: v })
  }

  return (
    <div className="main-inner">
      <div className="page-toolbar">
        <h1 className="page-title">邮箱账户</h1>
        <button type="button" className="btn-primary" onClick={openNew}>
          新增账户
        </button>
      </div>

      {msg && <p style={{ color: '#16a34a', margin: '0 0 12px' }}>{msg}</p>}
      {err && !modalOpen && (
        <p style={{ color: 'var(--danger)', margin: '0 0 12px' }}>{err}</p>
      )}

      <div className="card">
        <h2 style={{ marginTop: 0 }}>已有账户</h2>
        {list.length === 0 ? (
          <p className="muted">暂无账户。</p>
        ) : (
          <table>
            <thead>
              <tr>
                <th>名称</th>
                <th>邮箱</th>
                <th>SMTP</th>
                <th>IMAP</th>
                <th></th>
              </tr>
            </thead>
            <tbody>
              {list.map((a) => (
                <tr key={a.id}>
                  <td>{a.name}</td>
                  <td>{a.email}</td>
                  <td>
                    {a.smtp_host}:{a.smtp_port}
                  </td>
                  <td>
                    {a.imap_host}:{a.imap_port}
                  </td>
                  <td>
                    <button type="button" onClick={() => openEdit(a)}>
                      编辑
                    </button>{' '}
                    <button type="button" className="btn-danger" onClick={() => del(a.id)}>
                      删除
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>

      {modalOpen && (
        <div
          className="modal-mask"
          role="presentation"
          onClick={(e) => e.target === e.currentTarget && closeModal()}
        >
          <div className="modal modal-wide" onClick={(e) => e.stopPropagation()}>
            <h2>{editing ? `编辑账户 #${editing}` : '新增账户'}</h2>
            <form onSubmit={save}>
              <div className="form-row">
                <label>名称</label>
                <input value={form.name} onChange={set('name')} placeholder="工作 / 私人" required />
              </div>
              <div className="form-row">
                <label>邮箱</label>
                <input value={form.email} onChange={set('email')} type="email" required />
              </div>
              <div className="form-row">
                <label>密码 / 授权码</label>
                <input
                  value={form.password}
                  onChange={set('password')}
                  type="password"
                  placeholder={editing ? '留空不修改' : ''}
                />
              </div>
              <div className="form-row">
                <label>SMTP 主机</label>
                <input value={form.smtp_host} onChange={set('smtp_host')} placeholder="smtp.example.com" required />
              </div>
              <div className="form-row">
                <label>SMTP 端口</label>
                <input value={form.smtp_port} onChange={set('smtp_port')} type="number" required />
              </div>
              <div className="form-row">
                <label>IMAP 主机</label>
                <input value={form.imap_host} onChange={set('imap_host')} placeholder="imap.example.com" required />
              </div>
              <div className="form-row">
                <label>IMAP 端口</label>
                <input value={form.imap_port} onChange={set('imap_port')} type="number" required />
              </div>
              <div className="form-row">
                <label>使用 TLS/SSL</label>
                <label style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                  <input type="checkbox" checked={form.use_tls} onChange={set('use_tls')} style={{ width: 'auto' }} />
                  <span className="muted">建议开启</span>
                </label>
              </div>
              {err && (
                <div style={{ color: 'var(--danger)', marginTop: 8, fontSize: 14 }}>{err}</div>
              )}
              <div className="actions" style={{ marginTop: 16 }}>
                <button type="button" onClick={closeModal}>
                  取消
                </button>
                <button type="submit" className="btn-primary">
                  {editing ? '保存' : '创建'}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  )
}
