import { useState } from 'react'
import type { Category, Config } from '../types'
import { Modal } from './Modal'
import { IconClose, IconPlus } from './Icons'

interface Props {
  title: string
  categories: Category[]
  onSave: (category: Category) => Promise<Config>
  onDelete: (id: string) => Promise<Config>
  onConfigChange: (c: Config) => void
  onClose: () => void
}

/** 指令/规则共用的分类管理对话框：增删改 + 上下排序 */
export function CategoryManager({ title, categories, onSave, onDelete, onConfigChange, onClose }: Props) {
  const [newName, setNewName] = useState('')

  const add = async () => {
    const name = newName.trim()
    if (!name) return
    const maxOrder = categories.reduce((m, c) => Math.max(m, c.order), 0)
    onConfigChange(await onSave({ id: crypto.randomUUID(), name, order: maxOrder + 1 }))
    setNewName('')
  }

  const rename = async (cat: Category, name: string) => {
    if (name.trim() && name !== cat.name) {
      onConfigChange(await onSave({ ...cat, name: name.trim() }))
    }
  }

  const move = async (index: number, dir: -1 | 1) => {
    const target = categories[index + dir]
    const current = categories[index]
    if (!target) return
    await onSave({ ...current, order: target.order })
    onConfigChange(await onSave({ ...target, order: current.order }))
  }

  return (
    <Modal title={title} onClose={onClose} footer={<button className="btn" onClick={onClose}>完成</button>}>
      <div className="toolbar" style={{ marginBottom: 8 }}>
        <input
          className="input"
          style={{ flex: 1 }}
          placeholder="新分类名称"
          value={newName}
          onChange={(e) => setNewName(e.target.value)}
          onKeyDown={(e) => {
            if (e.key === 'Enter') void add()
          }}
        />
        <button className="btn primary" onClick={() => void add()}>
          <IconPlus />
          添加
        </button>
      </div>
      <div className="row-list">
        {categories.length === 0 && <div className="empty-hint">还没有分类</div>}
        {categories.map((cat, i) => (
          <div key={cat.id} className="row">
            <input
              className="input"
              style={{ flex: 1 }}
              defaultValue={cat.name}
              onBlur={(e) => void rename(cat, e.target.value)}
            />
            <div className="row-actions">
              <button className="btn small" disabled={i === 0} title="上移" onClick={() => void move(i, -1)}>
                上移
              </button>
              <button
                className="btn small"
                disabled={i === categories.length - 1}
                title="下移"
                onClick={() => void move(i, 1)}
              >
                下移
              </button>
              <button
                className="btn small danger"
                title="删除分类（其下条目归入未分类）"
                onClick={async () => onConfigChange(await onDelete(cat.id))}
              >
                <IconClose />
              </button>
            </div>
          </div>
        ))}
      </div>
    </Modal>
  )
}
