import Menu from "./Settings/Menu";
import General from "./Settings/General";
import Colors from "./Settings/Colors";
import Switch from "./Settings/Switch";
import Typography from "./Settings/Typography";
import Excludes from "./Settings/Excludes";
import CustomCss from "./Settings/CustomCss";
import Tools from "./Settings/Tools";
import Images from "./Settings/Images";
import Admin from "./Settings/Admin";
import Reading from "./Settings/Reading";

import {SettingsProvider} from "../contexts/SettingsContext";
import Advanced from "./Settings/Advanced";
import Videos from "./Settings/Videos";
import Animation from "./Settings/Animation";
import Analytics from "./Settings/Analytics";
import {saveSettings, showReviewPopup} from "../includes/functions";
import {Tooltip} from "react-tooltip";

const {useState, useRef, useEffect, useCallback} = React;

export default function Settings() {
    const {settings = {}, isPro} = dracula;

    settings.excludes = settings.excludes ? settings.excludes.filter((item, index) => !!item || index === 0) : [''];

    const [data, setData] = useState(settings);

    const [isLoading, setIsLoading] = useState(false);
    const [menu, setMenu] = useState(localStorage.getItem('dracula_settings_menu') || 'general');

    const updateSettings = (e, initData) => {

        if (!initData) {
            initData = data;
        }

        setIsLoading(true);

        const res = saveSettings(initData);
        res.then(() => setIsLoading(false));

        return res;
    }

    useEffect(() => {
        localStorage.setItem('dracula_settings_menu', menu);

        if (dracula.showReviewPopup) {
            setTimeout(() => {
                showReviewPopup()
            }, 5000);
        }
    }, [menu]);

    // Automatically save the settings when the data is updated
    const prevDataRef = useRef(data);
    const saveSettingsRef = useRef(null); // To store the save timeout

    // Debounce the save settings function
    const debounceSaveSettings = useCallback((newData, delay = 500) => {
        clearTimeout(saveSettingsRef.current); // Clear any existing save timeout
        saveSettingsRef.current = setTimeout(() => {
            saveSettings(newData);
        }, delay);
    }, []);

    useEffect(() => {
        if (!data.autoSave) return;

        const prevData = prevDataRef.current;
        let hasChanged = false;
        let delay = 500;

        // Check which data key has been changed and if it should trigger a save
        for (const key in data) {
            if (data[key] !== prevData[key]) {
                hasChanged = true;


                // Skip auto save for these keys
                if (['colorMode', 'images', 'videos',].includes(key)) {
                    return;
                }

                // Skip auto save for add new item in excludes, hides
                if (['excludes', 'hides'].includes(key) && Array.isArray(data[key]) && data[key]?.length > prevData[key]?.length && data[key][data[key]?.length - 1] === '') {
                    return;
                }

                // Delay for input fields
                if (['customCss', 'lightModeCSS', 'excludes', 'hides'].includes(key)) {
                    delay = 2000;
                }

            }
        }

        // If there's a change, call the debounce function
        if (hasChanged) {
            debounceSaveSettings(data);
        }

        // Update the ref with the current data state for the next effect run
        prevDataRef.current = data;
    }, [data, debounceSaveSettings]);

    return (
        <div className="dracula-settings">

            {!isPro &&
                <Tooltip
                    anchorSelect={'.dracula-pro-icon, .pro-disabled'}
                    place="right"
                    variant="warning"
                    content={wp.i18n.__('PRO Feature', 'dracula-dark-mode')}
                    className={`dracula-tooltip`}
                />
            }

            <SettingsProvider value={{data, setData, menu, isLoading, updateSettings}}>
                <Menu setMenu={setMenu}/>

                {'general' === menu && <General/>}
                {'advanced' === menu && <Advanced/>}
                {'colors' === menu && <Colors/>}
                {'typography' === menu && <Typography/>}
                {'toggle' === menu && <Switch/>}
                {'animation' === menu && <Animation/>}
                {'excludes' === menu && <Excludes/>}
                {'images' === menu && <Images/>}
                {'videos' === menu && <Videos/>}
                {'css' === menu && <CustomCss/>}
                {'admin' === menu && <Admin/>}
                {'reading' === menu && <Reading/>}
                {'analytics' === menu && <Analytics/>}
                {'tools' === menu && <Tools/>}

            </SettingsProvider>
        </div>
    )
}