import {forwardRef, useEffect, useImperativeHandle, useRef, useState} from "@wordpress/element";
import {__} from "@wordpress/i18n";
import Utility from "../../../_components/utility";
import Model from "../../../../../../../fields/specific-fields/model";
import Config from "../../../../../../../fields/specific-fields/config";
import {GetUtilitySettings} from "../../../../../../../../helpers/rest";
import {handleError} from "../../../../../../../../helpers/notifications";

const Copilot = forwardRef(({slug, active, toggle, loading, setLoading, hasUnsavedChanges, setHasUnsavedChanges, notifications}, ref) => {
    const utilityRef = useRef(null);
    // Actions states
    const [isDataFetched, setIsDataFetched] = useState(false);
    const [isDefaultsChecked, setIsDefaultsChecked] = useState(false);
    const [isModelsFetched, setIsModelsFetched] = useState(false);
    const [isConfigsFetched, setIsConfigsFetched] = useState(false);
    // Settings
    const settings = {
        'ai_model_id': useState(''),
        'config_id': useState(''),
    };
    const settingsDefault = {
        'ai_provider_id': useState(''),
    };

    const isDataReady = isDataFetched && isModelsFetched && isConfigsFetched;

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

    useImperativeHandle(ref, () => ({
        saved: () => {
            utilityRef.current.saved();
        },
        discard: () => {
            utilityRef.current.discard();
        }
    }));

    /**
     * Check default settings
     */
    const checkDefaultValues = async () => {
        setLoading(prev => prev + 1);
        try {
            // Get default settings
            const settingsInfo = [];
            if (!settings['ai_model_id'][0]) {
                settingsInfo.push({
                    key: "ai_model_id",
                    defaultValue: '',
                });
            }
            if (!settings['config_id'][0]) {
                settingsInfo.push({
                    key: "config_id",
                    defaultValue: '',
                });
            }
            if (settingsInfo.length > 0) {
                const defaults = await GetUtilitySettings(
                    'open-ai',
                    'copilot',
                    settingsInfo
                );
                // Setup default values
                settingsInfo.forEach(item => {
                    settings[item.key][1](defaults[item.key]);
                });
            }
        } catch (e) {
            handleError(e);
        }
        setIsDefaultsChecked(true);
        setLoading(prev => prev - 1);
    }

    return <Utility ref={utilityRef}
                    title={__("Copilot", 'limb-chatbot')}
                    slug={slug}
                    active={active}
                    toggle={toggle}
                    aiProviderId="gemini"
                    settings={settings}
                    settingsDefault={settingsDefault}
                    dataFetched={() => setIsDataFetched(true)}
                    isDataReady={isDataReady}
                    setLoading={setLoading}
                    setHasUnsavedChanges={setHasUnsavedChanges}
                    notifications={notifications}>
        <div className="lbaic-settings-column">
            <div className="lbaic-settings-column-in">
                <Model aiProviderId="gemini"
                       isAIProviderRequired={true}
                       isDataFetched={isDataFetched}
                       isDefaultsChecked={isDefaultsChecked}
                       modelId={settings['ai_model_id'][0]}
                       setModelId={settings['ai_model_id'][1]}
                       endpoints={['chat_completions']}
                       setFetched={setIsModelsFetched}
                       setLoading={setLoading}
                       notifications={notifications}/>
            </div>
            <div className="lbaic-settings-column-in">
                <Config aiProviderId="gemini"
                        isDataFetched={isDataFetched}
                        isDefaultsChecked={isDefaultsChecked}
                        configId={settings['config_id'][0]}
                        setConfigId={settings['config_id'][1]}
                        setFetched={setIsConfigsFetched}
                        setLoading={setLoading}
                        notifications={notifications}/>
            </div>
        </div>
    </Utility>
});

export default Copilot;