import store, { RootState } from '@/store';
import { App, ConfigProvider, MappingAlgorithm, theme } from 'antd';
import React, { useEffect, useState } from 'react';
import { Provider, useSelector } from 'react-redux';

export const isDarkTheme = window.matchMedia('(prefers-color-scheme: dark)');

const CP = ({ children, routes }: { children: any; routes: any }) => {
    const rootLayout = useSelector((state: RootState) => state.rootLayout);
    const [algorithm, setAlgorithm] = useState([theme.defaultAlgorithm]);
    useEffect(() => {
        let themeAlgorithms: MappingAlgorithm[] = [];
        if (rootLayout.themeCompact) {
            themeAlgorithms.push(theme.compactAlgorithm);
        }
        if (
            (rootLayout.themeMode === 'auto' && isDarkTheme.matches) ||
            rootLayout.themeMode === 'dark'
        ) {
            themeAlgorithms.push(theme.darkAlgorithm);
        }
        setAlgorithm(themeAlgorithms);
    }, [rootLayout.themeMode, rootLayout.themeCompact]);

    return (
        <ConfigProvider
            theme={{
                algorithm,
            }}
        >
            <App>
                {React.cloneElement(children, { ...children!.props, routes })}
            </App>
        </ConfigProvider >
    );
};

export default (props: { children: any; routes: any }) => {
    return (
        <Provider store={store}>
            <CP {...props} />
        </Provider>
    );
};
