import {forwardRef, useEffect, useImperativeHandle, useRef, useState} from "@wordpress/element";
import {__} from "@wordpress/i18n";
import {
    discardChanges,
    getInitialData,
    setSettingsDataToUpdate,
    setupSetting
} from "../../../../../../../../helpers";
import {handleError} from "../../../../../../../../helpers/notifications";
import {UTILITIES_HEADER_KEYS} from "../_data";
import {GetSettings} from "../../../../../../../../rest/settings";
import Checkbox from "../../../../../../../fields/checkbox";
import TableAccordionContentLoading from "../../../../../containers/table-accordion-content-loading";

const Chatbot = forwardRef(({slug, active, toggle, loading, setLoading, setSaving, hasUnsavedChanges, setHasUnsavedChanges, notifications}, ref) => {
    // Actions states
    const [localLoading, setLocalLoading] = useState(1);
    const [isDataFetched, setIsDataFetched] = useState(false);
    const [isDataReady, setIsDataReady] = useState(false);
    // Settings
    const settings = {};
    const settingsRef = useRef({});
    const settingsDefault = {
        'ai_provider_id': useState(''),
    };
    // Initial data
    const initialData = useRef(getInitialData(settings));
    const initialDataDefault = useRef(getInitialData(settingsDefault));
    // Settings prefix
    const keysPrefix = useRef('lbaic.ai_providers.deep-seek.utilities.chatbot');
    const keysPrefixDefault = useRef('lbaic.utilities.chatbot');
    // Storage key
    const storageKey = useRef('lbaic.settings.ai_providers.deep-seek.utilities.chatbot');
    const storageKeyDefault = useRef('lbaic.settings.utilities.chatbot');

    useImperativeHandle(ref, () => ({
        saved: () => {
            // Make the state as initial
            initialData.current = getInitialData(settings);
            initialDataDefault.current = getInitialData(settingsDefault);
            // Reset session storage
            sessionStorage.removeItem(storageKey.current);
            sessionStorage.removeItem(storageKeyDefault.current);
        },
        discard: () => {
            discardChanges(settings, initialData.current);
            discardChanges(settingsDefault, initialDataDefault.current);
        }
    }));

    useEffect(() => {
        Object.keys(settings).forEach(key => {
            settingsRef.current[key] = settings[key][0];
        });
    }, [settings]);

    useEffect(() => {
        if (active === slug) {
            fetchData();
        }
    }, [active, slug]);

    useEffect(() => {
        if (isDataReady) {
            // Local storage
            sessionStorage.setItem(storageKey.current, JSON.stringify(getInitialData(settings)));
            sessionStorage.setItem(storageKeyDefault.current, JSON.stringify(getInitialData(settingsDefault)));
            // Set settings data
            const dataToSave = setSettingsDataToUpdate(settings, initialData.current, `${keysPrefix.current}.`);
            const dataDefaultToSave = setSettingsDataToUpdate(settingsDefault, initialDataDefault.current, `${keysPrefixDefault.current}.`);
            const hasChanges = dataToSave?.length > 0 || dataDefaultToSave?.length > 0;
            if (hasUnsavedChanges !== hasChanges) {
                setHasUnsavedChanges(hasChanges);
            }
        }
    }, [isDataReady, settings, settingsDefault]);

    useEffect(() => {
        setIsDataReady(isDataFetched);
    }, [isDataFetched]);

    /**
     * Get saved settings
     */
    const fetchData = async () => {
        try {
            setLoading(prev => prev + 1);
            setLocalLoading(prev => prev + 1);
            const res = await GetSettings(LimbChatbot.rest.url, LimbChatbot.rest.nonce, {
                key: [...Object.keys(settings).map(key => `${keysPrefix.current}.${key}`), ...Object.keys(settingsDefault).map(key => `${keysPrefixDefault.current}.${key}`)],
            });
            if (res?.length) {
                for (const setting of res) {
                    const result = setupSetting(keysPrefix.current, setting, settings, initialData);
                    if (result !== -1) {
                        continue;
                    }
                    // Defaults
                    setupSetting(keysPrefixDefault.current, setting, settingsDefault, initialDataDefault);
                }
            }
            setIsDataFetched(true);
            setLoading(prev => prev - 1);
            setLocalLoading(prev => prev - 2);
        } catch (e) {
            handleError(e, notifications.set, {
                title: __("Failed to retrieve data.", 'limb-chatbot'),
                description: e.message ? __(e.message, 'limb-chatbot') : __("Please check your connection and try again.", 'limb-chatbot'),
            });
        }

        // Fetch other data
    }

    return <>
        <tr className={`lbaic-settings-table-accordion-body-in lbaic-settings-table-accordion-summary lbaic-settings-e-oaiu-table-summary${active === slug ? ' active' : ''}`}
            onClick={() => toggle(slug)}>
            <td className='lbaic-settings-table-accordion-body-item'>
                <div className='lbaic-settings-e-oaiu-table-item'>
                    <span className='lbaic-settings-table-accordion-body-label'>{__("Chatbot", 'limb-chatbot')}</span>
                </div>
            </td>
            <td className='lbaic-settings-table-accordion-body-item lbaic-settings-table-accordion-body-arrow'>
                <svg className='lbaic-settings-table-accordion-body-arrow-i' xmlns='http://www.w3.org/2000/svg' fill='none'
                     viewBox='0 0 24 24'>
                    <use href='#lbaic-settings-arrow'/>
                </svg>
            </td>
        </tr>
        <tr className={`lbaic-settings-table-accordion-body-in lbaic-settings-table-accordion-details${active === slug ? ' opened' : ''}`}>
            <td className='lbaic-settings-table-accordion-body-item lbaic-settings-table-accordion-details-in'
                colSpan={UTILITIES_HEADER_KEYS.length}>
                <div className='lbaic-settings-table-accordion-content lbaic-settings-e-oaiu-table-content'>
                    {localLoading > 0 && !isDataReady && <TableAccordionContentLoading/>}
                    <div className="lbaic-settings-column">
                        <div className="lbaic-settings-column-in">
                            <Checkbox label={__("Make default", 'limb-chatbot')}
                                      isChecked={settingsDefault['ai_provider_id'][0] === 'deep-seek'}
                                      toggleValue={() => settingsDefault['ai_provider_id'][1](settingsDefault['ai_provider_id'][0] === 'deep-seek' ? false : 'deep-seek')}
                                      desc={__("Check this to make DeepSeek the default AI provider for this utility.", 'limb-chatbot')}/>
                        </div>
                    </div>
                </div>
            </td>
        </tr>
    </>
});

export default Chatbot;