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

const initialFormData: CategoryFormData = {
  code: '',
  name: '',
  type: 'industry',
  description: '',
  sortOrder: 0,
  isActive: true,
};

export const initialState: CategoryState = {
  categories: [],
  searchKeyword: '',
  typeFilter: 'all',
  expandedIds: new Set(),
  dialogState: {
    open: false,
    editing: undefined,
    parent: undefined,
  },
  formData: initialFormData,
};

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(cat =>
          cat.id === action.payload.id
            ? { ...cat, ...action.payload.updates, updatedAt: new Date().toISOString() }
            : cat
        ),
      };

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

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

    case 'SET_TYPE_FILTER':
      return { ...state, typeFilter: action.payload };

    case 'TOGGLE_EXPAND':
      const newExpanded = new Set(state.expandedIds);
      if (newExpanded.has(action.payload)) {
        newExpanded.delete(action.payload);
      } else {
        newExpanded.add(action.payload);
      }
      return { ...state, expandedIds: newExpanded };

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

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

    default:
      return state;
  }
}