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

export default function Mailbox() {
  const { id } = useParams()
  const accountId = Number(id)
  const [searchParams] = useSearchParams()
  const mailbox = searchParams.get('mailbox') || 'INBOX'

  const [list, setList] = useState([])
  const [active, setActive] = useState(null)
  const [loading, setLoading] = useState(false)
  const [err, setErr] = useState('')

  useEffect(() => {
    setActive(null)
    setLoading(true)
    setErr('')
    api
      .listMessages(accountId, mailbox)
      .then((l) => setList(l || []))
      .catch((e) => setErr(e.message))
      .finally(() => setLoading(false))
  }, [accountId, mailbox])

  const closeDetail = useCallback(() => setActive(null), [])

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

  const open = async (m) => {
    setActive({ ...m, loading: true })
    try {
      const d = await api.getMessage(accountId, m.uid, mailbox)
      setActive(d)
    } catch (e) {
      setActive({ ...m, error: e.message, loading: false })
    }
  }

  return (
    <div className="main-inner">
      <div className="page-toolbar">
        <h1 className="page-title">{mailbox}</h1>
      </div>

      <div className="card" style={{ padding: 0 }}>
        {loading && <p className="muted" style={{ padding: 12 }}>加载中…</p>}
        {err && <p style={{ color: 'var(--danger)', padding: 12 }}>{err}</p>}
        {!loading && !err && list.length === 0 && (
          <p className="muted" style={{ padding: 12 }}>暂无邮件</p>
        )}
        <ul className="mail-list">
          {list.map((m) => (
            <li key={m.uid} className={m.seen ? '' : 'unseen'} onClick={() => open(m)}>
              <div className="subject">{m.subject || '(无主题)'}</div>
              <div className="from">
                {m.from} · {m.date && new Date(m.date).toLocaleString()}
              </div>
            </li>
          ))}
        </ul>
      </div>

      {active && (
        <div
          className="modal-mask"
          role="dialog"
          aria-modal="true"
          aria-labelledby="mail-subject"
          onClick={(e) => e.target === e.currentTarget && closeDetail()}
        >
          <div className="modal modal-mail" onClick={(e) => e.stopPropagation()}>
            <div className="modal-mail-toolbar">
              <h2 id="mail-subject">{active.subject || '(无主题)'}</h2>
              <button type="button" onClick={closeDetail}>
                关闭
              </button>
            </div>
            <div className="modal-mail-meta muted">
              <p>发件人: {active.from || '—'}</p>
              {active.to && active.to.length > 0 && (
                <p>收件人: {active.to.join(', ')}</p>
              )}
            </div>
            <div className="modal-mail-body">
              {active.loading && <p className="muted">加载中…</p>}
              {active.error && <p style={{ color: 'var(--danger)' }}>{active.error}</p>}
              {!active.loading && !active.error && active.html && (
                <iframe title="mail-html" srcDoc={active.html} />
              )}
              {!active.loading && !active.error && !active.html && (
                <pre>{active.text || ''}</pre>
              )}
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
