import { produce } from 'immer';
import { Reducer } from 'react';

import { ThemeAction } from '../demo/types';
import { createPersistReduxStore } from '../store';

import { defaultThemeConfig } from './constants';
import { ThemeState } from './types';

const ThemeReducer: Reducer<ThemeState, ThemeAction> = produce((draft, action) => {
    switch (action.type) {
        case 'change_mode':
            draft.mode = action.value;
            break;
        case 'toggle_mode':
            draft.mode = draft.mode === 'dark' ? 'light' : 'dark';
            break;
        case 'change_compact':
            draft.compact = action.value;
            break;
        case 'toggle_compact':
            draft.compact = !draft.compact;
            break;
        default:
            break;
    }
});

export const useThemeStore = createPersistReduxStore(ThemeReducer, defaultThemeConfig, {
    name: 'theme',
    partialize: (state) => ({ mode: state.mode, compact: state.compact }),
});
