import { theme } from 'antd';
import { debounce, omit } from 'lodash';
import { useCallback, useMemo } from 'react';
import { useShallow } from 'zustand/react/shallow';

import { useThemeStore } from './store';
import { ThemeMode } from './types';

/**
 * 获取主题状态
 */
export const useTheme = () => useThemeStore(useShallow((state) => omit(state, ['dispatch'])));

/**
 * 获取Antd主题算法
 */
export const useAntdAlgorithm = () => {
    const { mode, compact } = useTheme();
    return useMemo(() => {
        const result = [compact ? theme.compactAlgorithm : theme.defaultAlgorithm];
        if (mode === 'dark') result.push(theme.darkAlgorithm);
        return result;
    }, [mode, compact]);
};

/**
 * 主题操作函数
 */
export const useThemeActions = () => {
    const dispatch = useThemeStore((state) => state.dispatch);
    return {
        changeMode: useCallback(
            debounce(
                (v: `${ThemeMode}`) => () => dispatch({ type: 'change_mode', value: v }),
                100,
                {},
            ),
            [],
        ),
        toggleMode: useCallback(
            debounce(() => dispatch({ type: 'toggle_mode' }), 100, {}),
            [],
        ),
        changeCompact: useCallback(
            (v: boolean) => dispatch({ type: 'change_compact', value: v }),
            [],
        ),
        toggleCompact: useCallback(() => dispatch({ type: 'toggle_compact' }), []),
    };
};
