import React, { useState } from 'react';
import { Category } from '../types';
import './CategoryManager.css';

interface CategoryManagerProps {
  categories: Category[];
  onAddCategory: (name: string) => void;
  onDeleteCategory: (id: string) => void;
}

const CategoryManager: React.FC<CategoryManagerProps> = ({
  categories,
  onAddCategory,
  onDeleteCategory,
}) => {
  const [isAdding, setIsAdding] = useState(false);
  const [newCategoryName, setNewCategoryName] = useState('');

  const handleAdd = () => {
    if (newCategoryName.trim()) {
      onAddCategory(newCategoryName.trim());
      setNewCategoryName('');
      setIsAdding(false);
    }
  };

  return (
    <div className="category-manager">
      <div className="category-header">
        <h3>分类管理</h3>
        <button
          className="add-category-btn"
          onClick={() => setIsAdding(true)}
        >
          + 添加分类
        </button>
      </div>

      {isAdding && (
        <div className="add-category-form">
          <input
            type="text"
            value={newCategoryName}
            onChange={(e) => setNewCategoryName(e.target.value)}
            placeholder="输入分类名称"
            onKeyPress={(e) => e.key === 'Enter' && handleAdd()}
            autoFocus
          />
          <button onClick={handleAdd}>确定</button>
          <button onClick={() => {
            setIsAdding(false);
            setNewCategoryName('');
          }}>
            取消
          </button>
        </div>
      )}

      <div className="category-list">
        {categories.map((cat) => (
          <div key={cat.id} className="category-item">
            <span>{cat.name}</span>
            {cat.id !== 'default' && (
              <button
                className="delete-btn"
                onClick={() => onDeleteCategory(cat.id)}
                title="删除分类"
              >
                ✕
              </button>
            )}
          </div>
        ))}
      </div>
    </div>
  );
};

export default CategoryManager;
