import GeneralSettings from "./Settings/GeneralSettings";
import StickySettings from "./Settings/StickySettings";
import StatisticsSettings from "./Settings/StatisticsSettings";
import Header from "./Settings/Header";
import CustomCSS from "./Settings/CustomCSS";
import PopupSettings from "./Settings/PopupSettings";

import {showReviewPopup, useMounted} from "../includes/functions";
import Tools from "./Settings/Tools";
import PlaylistSettings from "./Settings/PlaylistSettings";
import {Tooltip} from "react-tooltip";

const {useState, useEffect, useRef} = React;

export default function Settings() {

    const {settings, isPro} = radioPlayer;

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

    const tabs = [
        {
            key: 'general',
            title: wp.i18n.__('General Settings', 'radio-player'),
        },
        {
            key: 'sticky',
            title: wp.i18n.__('Sticky Player Settings', 'radio-player'),
        },
        {
            key: 'popup',
            title: wp.i18n.__('Popup Player Settings', 'radio-player'),
        },
        {
            key: 'playlist',
            title: wp.i18n.__('Playlist Settings', 'radio-player'),
        },

        {
            key: 'statistics',
            title: wp.i18n.__('Statistics Settings', 'radio-player'),
        },
        {
            key: 'css',
            title: wp.i18n.__('Custom CSS', 'radio-player'),
        },
        {
            key: 'tools',
            title: wp.i18n.__('Tools', 'radio-player'),
        },
    ];

    // Fetch the tab parameter from the URL
    const urlParams = new URLSearchParams(window.location.search);
    const tabFromUrl = urlParams.get('tab');

    // Fallback to local storage and then to default values if necessary
    let savedTab = localStorage.getItem('radio_player_settings_tab');
    const tabKeys = tabs.map(t => t.key);

    savedTab = (!savedTab || !tabKeys.includes(savedTab)) ? 'general' : savedTab;

    // Prioritize URL parameter, then local storage, and finally the default value
    const initialTab = tabFromUrl || savedTab;

    const [tab, setTab] = useState(initialTab);

    const [isUpdating, setIsUpdating] = useState(false);

    const updateSettings = () => {

        setIsUpdating(true);

        wp.ajax
            .post('rp_update_settings', {
                data,
                nonce: radioPlayer.nonce,
            })
            .done(() => {
                Swal.fire({
                    icon: 'success',
                    title: wp.i18n.__('Settings saved successfully', 'radio-player'),
                    showConfirmButton: false,
                    timer: 2000,
                    toast: true,
                    position: 'top-end',
                    customClass: {
                        container: 'radio-player-swal radio-player-swal-toast',
                    }
                });
            })
            .fail((error) => {
                console.log(error);

                Swal.fire({
                    icon: 'error',
                    title: 'Something went wrong',
                    showConfirmButton: false,
                    timer: 1500,
                    toast: true,
                    position: 'top-end',
                });
            })
            .always(() => {
                setIsUpdating(false);
            });
    }

    useEffect(() => {
        localStorage.setItem('radio_player_settings_tab', tab);

        if (radioPlayer.showReviewPopup) {
            setTimeout(() => {
                showReviewPopup()
            }, 5000);
        }

    }, [tab]);

    // Automatically save the settings when the data is updated
    const prevDataRef = useRef(data);

    const isMounted = useMounted();
    useEffect(() => {
        if (!isMounted || !data.autoSave) return;

        let delay = 100;

        // Get the previous data state from the ref
        const prevData = prevDataRef.current;

        // Check which data key has been changed
        for (const key in data) {
            if (data[key] !== prevData[key]) {

                if ([
                    'popupTriggers',
                    'minimizePlayerImage',
                    'volume',
                    'customCSS',
                    'popupHeaderContent',
                    'popupFooterContent',
                    '',
                ].includes(key)) {
                    return;
                }

                if ([
                    'stickyTriggers',
                    'reportingEmail',
                    'popupWidth',
                    'popupHeight',
                    '',
                    '',
                    '',
                ].includes(key)) {
                    delay = 2000;
                }


                break;
            }
        }

        // Update the ref with the current data state
        prevDataRef.current = data;

        const handler = setTimeout(() => {
            updateSettings()
        }, delay);

        return () => clearTimeout(handler);

    }, [data]);

    return (
        <>

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

            <Header updateSettings={updateSettings} isUpdating={isUpdating}/>

            <div className="radio-player-settings-menu">
                {
                    tabs.map(({key, title, icon}) => {
                        return (
                            <div
                                key={key}
                                className={`menu-item ${key} ${tab === key ? 'active' : ''}`}
                                onClick={() => setTab(key)}
                            >
                                <img className={`settings-icon`}
                                     src={`${radioPlayer.plugin_url}/assets/images/settings/${key}.svg`}/>
                                <span className="settings-title">{title}</span>
                            </div>
                        )
                    })
                }
            </div>

            {tab === 'general' && <GeneralSettings data={data} setData={setData}/>}
            {tab === 'sticky' && <StickySettings data={data} setData={setData}/>}
            {tab === 'popup' && <PopupSettings data={data} setData={setData}/>}
            {tab === 'playlist' && <PlaylistSettings data={data} setData={setData}/>}
            {tab === 'statistics' && <StatisticsSettings data={data} setData={setData}/>}
            {tab === 'css' && <CustomCSS data={data} setData={setData}/>}
            {tab === 'tools' && <Tools data={data} setData={setData}/>}
        </>
    )


}