import {useEffect, useState} from "@wordpress/element";
import {useSelect} from '@wordpress/data';
import {store as coreDataStore} from '@wordpress/core-data';
import Utilities from "./containers/utilities";
import Nav from "./containers/nav";
import Content from "./containers/content";
import {createBrowserRouter, RouterProvider} from 'react-router-dom';
import NotificationLayout from "../../containers/notification-layout";
import PopupLayout from "../../containers/popup-layout";
import {NotificationsContext} from "../../contexts/notifications";
import {getRoutesRootPath} from "../../../helpers";
import TutorialLayout from "../../containers/tutorial-layout";
import FieldMenuLayout from "../../containers/field-menu-layout";
import DrawerLayout from "../../containers/drawer-layout";
import {DeleteSettings, GetSettings} from "../../../rest/settings";
import Onboarding, {ONBOARDING_KEY_PREFIX} from "./components/onboarding";
import {handleError} from "../../../helpers/notifications";
import {DEFAULT_CHATBOT_SETTINGS_KEY_PREFIX} from "../../../data/chatbot/settings";

function BrowserRouterElement({isOnboardingActive, showOnboarding, ...contentProps}) {
    return (
        <div className='lbaic-settings'>
            <Nav/>
            <Content
                key={showOnboarding}
                isOnboardingActive={isOnboardingActive}
                {...contentProps}
            />
        </div>
    );
}

export default function Settings() {
    const [notifications, setNotifications] = useState([]);
    const [chatbotPreview, setChatbotPreview] = useState({
        uuid: 'default',
        utility: {}
    });
    // Onboarding
    const [checkingOnboardingStatus, setCheckingOnboardingStatus] = useState(1);
    const [showOnboarding, setShowOnboarding] = useState(false);
    const [onboardingSettings, setOnboardingSettings] = useState(null);
    const isOnboardingActive = checkingOnboardingStatus > 0 || showOnboarding;
    // Current user
    const currentUser = useSelect((select) =>
            select(coreDataStore).getCurrentUser(),
        []
    );
    const userId = currentUser?.id;

    /**
     * Clear all cached settings data from sessionStorage
     */
    const clearSettingsCache = () => {
        for (let i = sessionStorage.length - 1; i >= 0; i--) {
            const key = sessionStorage.key(i);
            if (key && key.startsWith('lbaic.settings.')) {
                sessionStorage.removeItem(key);
            }
        }
    };

    /**
     * Delete all preview data
     */
    const deleteAllPreviewData = () => {
        try {
            DeleteSettings(LimbChatbot.rest.url, LimbChatbot.rest.nonce, {
                suffix: "preview",
            });
        } catch (e) {
            handleError(e);
        }
    }

    /**
     * Check onboarding status
     *
     * @return {Promise<void>}
     */
    const checkOnboardingStatus = async () => {
        setCheckingOnboardingStatus(prev => prev + 1);
        try {
            const res = await GetSettings(LimbChatbot.rest.url, LimbChatbot.rest.nonce, {
                key: [
                    ONBOARDING_KEY_PREFIX + 'status',
                    ONBOARDING_KEY_PREFIX + 'processes',
                    DEFAULT_CHATBOT_SETTINGS_KEY_PREFIX + 'config_id',
                    ONBOARDING_KEY_PREFIX + 'step_2.status'
                ],
            });
            setOnboardingSettings(res);
            // Status
            const status = res.find(item => item.key === ONBOARDING_KEY_PREFIX + 'status')?.value;
            if (!status || status === 'start') {
                // Start onboarding
                setShowOnboarding(true);
            }
        } catch (e) {
            handleError(e);
        }
        setCheckingOnboardingStatus(prev => prev - 2);
    }

    useEffect(() => {
        // Reset all cached data
        clearSettingsCache();
        // Delete all preview data
        deleteAllPreviewData();
        // Check onboarding status
        checkOnboardingStatus();
    }, []);

    /**
     * BrowserRouter
     *
     * @type {Router}
     */
    const router = createBrowserRouter([
        {
            path: getRoutesRootPath(),
            element: (
                <BrowserRouterElement
                    isOnboardingActive={isOnboardingActive}
                    showOnboarding={showOnboarding}
                    chatbotPreview={chatbotPreview}
                    setChatbotPreview={setChatbotPreview}
                    userId={userId}
                />
            ),
        },
    ], {
        future: {
            v7_startTransition: true,
            v7_relativeSplatPath: true,
            v7_fetcherPersist: true,
            v7_normalizeFormMethod: true,
            v7_partialHydration: true,
            v7_skipActionErrorRevalidation: true,
        },
    });

    /**
     * On onboarding popup close
     */
    const onOnboardingClose = () => {
        setShowOnboarding(false);
        // Clear all cached data to force refetch
        clearSettingsCache();
    }

    return (
        <>
            <Utilities/>
            <NotificationsContext.Provider value={{get: notifications, set: setNotifications}}>
                <RouterProvider router={router}/>
                <PopupLayout/>
                {showOnboarding && (
                    <Onboarding
                        settings={onboardingSettings}
                        onClose={onOnboardingClose}
                        userId={userId}
                        chatbotPreview={chatbotPreview}
                        setChatbotPreview={setChatbotPreview}
                    />
                )}
                <NotificationLayout/>
                <FieldMenuLayout/>
                <DrawerLayout/>
                {/*<TutorialLayout />*/}
            </NotificationsContext.Provider>
        </>
    )
}