import { useEffect, useState } from 'react'
import { useNavigate, useParams } from 'react-router-dom'
import { api } from '../api/client.js'

export default function Compose() {
  const { id } = useParams()
  const accountId = Number(id)
  const nav = useNavigate()
  const [accounts, setAccounts] = useState([])
  const [form, setForm] = useState({ to: '', subject: '', body: '', html: false })
  const [sending, setSending] = useState(false)
  const [err, setErr] = useState('')
  const [msg, setMsg] = useState('')

  useEffect(() => {
    api
      .listAccounts()
      .then((rows) => setAccounts(Array.isArray(rows) ? rows : []))
      .catch(() => {})
  }, [])

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

  const send = async (e) => {
    e.preventDefault()
    setErr(''); setMsg(''); setSending(true)
    try {
      await api.send(accountId, form)
      setMsg('发送成功')
      setForm({ to: '', subject: '', body: '', html: false })
    } catch (e) { setErr(e.message) }
    finally { setSending(false) }
  }

  const acc = accounts.find((a) => a.id === accountId)

  return (
    <div className="main-inner">
      <h1 className="page-title">撰写</h1>
      <p className="muted">{acc ? acc.email : `#${accountId}`}</p>

      <div className="card">
        <form onSubmit={send}>
          <div className="form-row"><label>切换账户</label>
            <select value={accountId} onChange={(e) => nav(`/admin/compose/${e.target.value}`)}>
              {accounts.map((a) => (
                <option key={a.id} value={a.id}>{a.name} &lt;{a.email}&gt;</option>
              ))}
            </select>
          </div>
          <div className="form-row"><label>收件人</label><input value={form.to} onChange={set('to')} type="email" required /></div>
          <div className="form-row"><label>主题</label><input value={form.subject} onChange={set('subject')} required /></div>
          <div className="form-row">
            <label>HTML</label>
            <label style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
              <input type="checkbox" checked={form.html} onChange={set('html')} style={{ width: 'auto' }} />
              <span className="muted">按 HTML 发送</span>
            </label>
          </div>
          <div className="form-row" style={{ alignItems: 'start' }}>
            <label>正文</label>
            <textarea value={form.body} onChange={set('body')} rows={10} required />
          </div>
          <div style={{ marginTop: 8 }}>
            <button type="submit" className="btn-primary" disabled={sending}>
              {sending ? '发送中…' : '发送'}
            </button>
          </div>
          {err && <div style={{ color: 'var(--danger)', marginTop: 8 }}>{err}</div>}
          {msg && <div style={{ color: '#16a34a', marginTop: 8 }}>{msg}</div>}
        </form>
      </div>
    </div>
  )
}
