import { useEffect, useState } from 'react'
import Modal from '../../../components/Modal.jsx'
import { api } from '../../../api/client.js'

export default function WikiEditor({ slug, onClose, onSaved }) {
  const isEdit = Boolean(slug)
  const [form, setForm] = useState({ slug: '', title: '', body: '' })
  const [loading, setLoading] = useState(isEdit)
  const [busy, setBusy] = useState(false)
  const [error, setError] = useState('')

  useEffect(() => {
    if (!isEdit) return
    let active = true
    api.admin
      .getWiki(slug)
      .then((p) => active && setForm({ slug: p.slug, title: p.title, body: p.body || '' }))
      .catch(() => active && setError('Could not load this page.'))
      .finally(() => active && setLoading(false))
    return () => {
      active = false
    }
  }, [slug, isEdit])

  const set = (k) => (e) => setForm((f) => ({ ...f, [k]: e.target.value }))

  async function save() {
    if (!form.title.trim()) return setError('Title is required.')
    if (!isEdit && !/^[a-z0-9-]+$/.test(form.slug)) return setError('Slug must be lowercase letters, numbers, and dashes.')
    setBusy(true)
    setError('')
    try {
      if (isEdit) await api.admin.updateWiki(slug, { title: form.title.trim(), body: form.body })
      else await api.admin.createWiki({ slug: form.slug, title: form.title.trim(), body: form.body })
      onSaved()
    } catch (err) {
      setError(err.message || 'Could not save.')
      setBusy(false)
    }
  }

  async function remove() {
    if (!confirm('Delete this wiki page?')) return
    setBusy(true)
    try {
      await api.admin.deleteWiki(slug)
      onSaved()
    } catch (err) {
      setError(err.message || 'Could not delete.')
      setBusy(false)
    }
  }

  return (
    <Modal
      title={isEdit ? 'Edit wiki page' : 'New wiki page'}
      onClose={onClose}
      width={640}
      footer={
        <>
          {isEdit && (
            <button onClick={remove} disabled={busy} className="sans" style={delStyle}>
              Delete
            </button>
          )}
          <button onClick={onClose} disabled={busy} className="pill">
            Cancel
          </button>
          <button onClick={save} disabled={busy || loading} className="btn btn-primary btn-sq">
            {busy ? 'Saving…' : 'Save'}
          </button>
        </>
      }
    >
      {loading ? (
        <span className="spin" />
      ) : (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          {error && <p className="sans" style={{ margin: 0, color: '#d98b84', fontSize: '0.85rem' }}>{error}</p>}
          <label>
            <span className="field-label">Slug</span>
            <input
              type="text"
              value={form.slug}
              onChange={set('slug')}
              disabled={isEdit}
              className="input"
              style={{ fontFamily: 'ui-monospace,Menlo,monospace', opacity: isEdit ? 0.6 : 1 }}
              placeholder="new-player-guide"
            />
          </label>
          <label>
            <span className="field-label">Title</span>
            <input type="text" value={form.title} onChange={set('title')} className="input" />
          </label>
          <label>
            <span className="field-label">Body (HTML — use &lt;h2&gt; for the table of contents)</span>
            <textarea value={form.body} onChange={set('body')} className="textarea" style={{ minHeight: 260 }} />
          </label>
        </div>
      )}
    </Modal>
  )
}

const delStyle = {
  border: '1px solid #6e3b38',
  borderRadius: 999,
  padding: '7px 16px',
  background: 'rgba(110,59,56,0.18)',
  color: '#d98b84',
  fontSize: '0.86rem',
  cursor: 'pointer',
  marginRight: 'auto',
}
