import { useEffect, useState } from 'react'
import { admin } from '../api/endpoints'
import { useToast } from '../context/ToastContext'
import { Card, Button, Input, Modal } from './ui'
import { Edit, Trash, Plus } from '../components/icons'

export default function AdminCategories() {
  const toast = useToast()
  const [items, setItems] = useState([])
  const [editing, setEditing] = useState(null)
  const [name, setName] = useState('')

  const load = () => admin.categories().then(setItems).catch(() => {})
  useEffect(() => {
    load()
  }, [])

  const openNew = () => {
    setEditing({ id: null })
    setName('')
  }
  const openEdit = (c) => {
    setEditing(c)
    setName(c.name)
  }

  const save = async () => {
    if (!name.trim()) return
    try {
      if (editing.id) await admin.updateCategory(editing.id, { name })
      else await admin.createCategory({ name })
      toast.success('Saved')
      setEditing(null)
      load()
    } catch {
      toast.error('Could not save')
    }
  }

  const remove = async (c) => {
    if (!confirm(`Delete category "${c.name}"? Videos will be uncategorized.`)) return
    try {
      await admin.deleteCategory(c.id)
      load()
    } catch {
      toast.error('Could not delete')
    }
  }

  const move = async (index, dir) => {
    const next = [...items]
    const target = index + dir
    if (target < 0 || target >= next.length) return
    ;[next[index], next[target]] = [next[target], next[index]]
    setItems(next)
    await admin.reorderCategories(next.map((c) => c.id)).catch(() => {})
  }

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <h1 className="text-xl font-extrabold">Categories</h1>
        <Button onClick={openNew}>
          <span className="inline-flex items-center gap-1">
            <Plus width={15} height={15} /> New
          </span>
        </Button>
      </div>

      <Card>
        <ul className="divide-y divide-gray-100 dark:divide-gray-800">
          {items.map((c, i) => (
            <li key={c.id} className="flex items-center gap-3 py-2.5">
              <div className="flex flex-col">
                <button onClick={() => move(i, -1)} className="text-gray-400 hover:text-gray-700 dark:hover:text-gray-200">▲</button>
                <button onClick={() => move(i, 1)} className="text-gray-400 hover:text-gray-700 dark:hover:text-gray-200">▼</button>
              </div>
              <span className="flex-1 font-medium">{c.name}</span>
              <span className="text-xs text-gray-400">{c.videos_count ?? 0} videos</span>
              <button onClick={() => openEdit(c)} className="rounded-lg p-2 text-gray-500 hover:bg-gray-100 dark:hover:bg-gray-800">
                <Edit width={16} height={16} />
              </button>
              <button onClick={() => remove(c)} className="rounded-lg p-2 text-rose-500 hover:bg-rose-50 dark:hover:bg-rose-900/20">
                <Trash width={16} height={16} />
              </button>
            </li>
          ))}
          {items.length === 0 && <li className="py-6 text-center text-gray-400">No categories yet.</li>}
        </ul>
      </Card>

      <Modal open={!!editing} onClose={() => setEditing(null)} title={editing?.id ? 'Edit category' : 'New category'}>
        <div className="space-y-4">
          <Input label="Name" value={name} onChange={(e) => setName(e.target.value)} autoFocus />
          <div className="flex justify-end gap-2">
            <Button variant="ghost" onClick={() => setEditing(null)}>
              Cancel
            </Button>
            <Button onClick={save}>Save</Button>
          </div>
        </div>
      </Modal>
    </div>
  )
}
