import { CategoryState, CategoryAction, CategoryFormData } from './types';

// 初始状态
export const initialCategoryState: CategoryState = {
  categories: [],
  searchKeyword: '',
  categoryFilter: 'all',
  dialogState: {
    open: false,
    editing: null,
  },
  formData: {
    code: '',
    name: '',
    category: 'other',
    value: '',
    label: '',
    sortOrder: 0,
    description: '',
    isActive: true,
  },
};

// 初始表单数据
export const initialFormData: CategoryFormData = {
  code: '',
  name: '',
  category: 'other',
  value: '',
  label: '',
  sortOrder: 0,
  description: '',
  isActive: true,
};

// Reducer
export function categoryReducer(state: CategoryState, action: CategoryAction): CategoryState {
  switch (action.type) {
    case 'SET_CATEGORIES':
      return {
        ...state,
        categories: action.payload,
      };

    case 'ADD_CATEGORY':
      return {
        ...state,
        categories: [...state.categories, action.payload],
      };

    case 'UPDATE_CATEGORY':
      return {
        ...state,
        categories: state.categories.map(category =>
          category.id === action.payload.id
            ? { ...category, ...action.payload.updates, updatedAt: new Date().toISOString() }
            : category
        ),
      };

    case 'DELETE_CATEGORY':
      return {
        ...state,
        categories: state.categories.filter(category => category.id !== action.payload),
      };

    case 'SET_SEARCH_KEYWORD':
      return {
        ...state,
        searchKeyword: action.payload,
      };

    case 'SET_CATEGORY_FILTER':
      return {
        ...state,
        categoryFilter: action.payload,
      };

    case 'SET_DIALOG_STATE':
      return {
        ...state,
        dialogState: action.payload,
        formData: action.payload.editing
          ? {
              code: action.payload.editing.code,
              name: action.payload.editing.name,
              category: action.payload.editing.category,
              value: action.payload.editing.value,
              label: action.payload.editing.label,
              sortOrder: action.payload.editing.sortOrder,
              description: action.payload.editing.description || '',
              isActive: action.payload.editing.isActive,
            }
          : initialFormData,
      };

    case 'SET_FORM_DATA':
      return {
        ...state,
        formData: {
          ...state.formData,
          ...action.payload,
        },
      };

    default:
      return state;
  }
}