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

const EMPTY = { slug: '', title: '', description: '', sort_order: 0 }

export default function WikiCategories({ onClose }) {
  const [cats, setCats] = useState([])
  const [editing, setEditing] = useState(null) // null = create mode, else category id
  const [form, setForm] = useState(EMPTY)
  const [busy, setBusy] = useState(false)
  const [error, setError] = useState('')

  const load = useCallback(() => {
    api.admin
      .listWikiCategories()
      .then(setCats)
      .catch(() => setError('Could not load sections.'))
  }, [])

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

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

  function startEdit(c) {
    setEditing(c.id)
    setForm({ slug: c.slug, title: c.title, description: c.description || '', sort_order: c.sort_order })
    setError('')
  }

  function reset() {
    setEditing(null)
    setForm(EMPTY)
  }

  async function save() {
    if (!form.title.trim()) return setError('Title is required.')
    if (!editing && !/^[a-z0-9-]+$/.test(form.slug)) {
      return setError('Slug must be lowercase letters, numbers, and dashes.')
    }
    setBusy(true)
    setError('')
    const payload = {
      title: form.title.trim(),
      description: form.description.trim(),
      sort_order: Number(form.sort_order) || 0,
    }
    try {
      if (editing) await api.admin.updateWikiCategory(editing, payload)
      else await api.admin.createWikiCategory({ slug: form.slug, ...payload })
      reset()
      load()
    } catch (err) {
      setError(err.message || 'Could not save section.')
    } finally {
      setBusy(false)
    }
  }

  async function remove(c) {
    if (!confirm(`Delete section "${c.title}"? Its ${c.page_count} page(s) become uncategorized.`)) return
    setBusy(true)
    try {
      await api.admin.deleteWikiCategory(c.id)
      if (editing === c.id) reset()
      load()
    } catch (err) {
      setError(err.message || 'Could not delete section.')
    } finally {
      setBusy(false)
    }
  }

  return (
    <Modal
      title="Wiki sections"
      onClose={onClose}
      width={640}
      footer={
        <button onClick={onClose} className="pill">
          Done
        </button>
      }
    >
      <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
        {error && <p className="sans" style={{ margin: 0, color: '#d98b84', fontSize: '0.85rem' }}>{error}</p>}

        {/* Create / edit form */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap' }}>
            <label style={{ flex: '1 1 160px' }}>
              <span className="field-label">Slug</span>
              <input
                type="text"
                value={form.slug}
                onChange={set('slug')}
                disabled={Boolean(editing)}
                className="input"
                style={{ fontFamily: 'ui-monospace,Menlo,monospace', opacity: editing ? 0.6 : 1 }}
                placeholder="guides"
              />
            </label>
            <label style={{ flex: '1 1 160px' }}>
              <span className="field-label">Title</span>
              <input type="text" value={form.title} onChange={set('title')} className="input" />
            </label>
            <label style={{ flex: '0 0 90px' }}>
              <span className="field-label">Order</span>
              <input type="number" value={form.sort_order} onChange={set('sort_order')} className="input" />
            </label>
          </div>
          <label>
            <span className="field-label">Description</span>
            <input
              type="text"
              value={form.description}
              onChange={set('description')}
              className="input"
              maxLength={400}
              placeholder="Shown under the section heading on the wiki home."
            />
          </label>
          <div style={{ display: 'flex', gap: 10 }}>
            <button onClick={save} disabled={busy} className="btn btn-primary btn-sq">
              {editing ? 'Save section' : '+ Add section'}
            </button>
            {editing && (
              <button onClick={reset} disabled={busy} className="pill">
                Cancel edit
              </button>
            )}
          </div>
        </div>

        {/* Existing categories */}
        <div className="panel-flat">
          <table className="adm-table">
            <thead>
              <tr>
                <th className="adm-th">Section</th>
                <th className="adm-th">Slug</th>
                <th className="adm-th">Pages</th>
                <th className="adm-th" />
              </tr>
            </thead>
            <tbody>
              {cats.map((c) => (
                <tr key={c.id}>
                  <td className="adm-td" style={{ color: 'var(--head)' }}>
                    {c.title}
                  </td>
                  <td className="adm-td" style={{ fontFamily: 'ui-monospace,Menlo,monospace', color: 'var(--accent)' }}>
                    {c.slug}
                  </td>
                  <td className="adm-td dim">{c.page_count}</td>
                  <td className="adm-td" style={{ textAlign: 'right', whiteSpace: 'nowrap' }}>
                    <span className="link-accent" onClick={() => startEdit(c)}>
                      Edit
                    </span>
                    <span style={{ color: 'var(--line)', margin: '0 8px' }}>·</span>
                    <span className="link-accent" style={{ color: '#d98b84' }} onClick={() => remove(c)}>
                      Delete
                    </span>
                  </td>
                </tr>
              ))}
              {cats.length === 0 && (
                <tr>
                  <td className="adm-td dim" colSpan={4}>
                    No sections yet.
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </div>
    </Modal>
  )
}
