import {useState, useEffect, useRef} from "@wordpress/element";
import {__} from "@wordpress/i18n";
import PopupContainer from "../../container";
import Button from "../../../button/_";
import Model from "../../../fields/specific-fields/model";
import Config from "../../../fields/specific-fields/config";
import {GetSetting} from "../../../../rest/settings";
import {GetDefaultSettings} from "../../../../helpers/rest";

export default function RegenerateDatasetsPopup({
                                                    close,
                                                    onRegenerate,
                                                    notifications,
                                                    loading = false
                                                }) {
    // Data indexing fields
    const [indexingAIProviderId, setIndexingAIProviderId] = useState(null);
    const [indexingModelId, setIndexingModelId] = useState('');
    const [indexingConfigId, setIndexingConfigId] = useState('');

    const [isDataFetched, setIsDataFetched] = useState(false);
    const [isDefaultsChecked, setIsDefaultsChecked] = useState(false);
    const [chatbotAIProviderId, setChatbotAIProviderId] = useState(null);
    const [chatbotAIProviderFetched, setChatbotAIProviderFetched] = useState(false);
    const [errors, setErrors] = useState({
        indexingModel: false,
        indexingConfig: false
    });
    const indexingConfigRef = useRef(null);


    /**
     * Setup default settings for data indexing (embedding utility)
     */
    const setupDataIndexingDefaults = async () => {
        const settingsKeys = [
            {
                key: 'ai_model_id',
                defaultValue: '',
            },
            {
                key: 'config_id',
                defaultValue: '',
            }
        ];
        try {
            const defaults = await GetDefaultSettings('embedding', settingsKeys);
            if (defaults.ai_model_id) {
                setIndexingModelId(defaults.ai_model_id);
            }
            if (defaults.config_id) {
                setIndexingConfigId(defaults.config_id);
            }
        } catch (e) {
            console.error('Failed to fetch data indexing defaults:', e);
        }
    };

    useEffect(() => {
        let timer;
        const initializeDefaults = async () => {
            // Fetch chatbot AI provider first
            if (!chatbotAIProviderFetched) {
                try {
                    const setting = await GetSetting(
                        LimbChatbot.rest.url,
                        LimbChatbot.rest.nonce,
                        'lbaic.utilities.chatbot.ai_provider_id'
                    );
                    if (setting?.value) {
                        setChatbotAIProviderId(setting.value);
                        setIndexingAIProviderId(setting.value);
                    }
                } catch (e) {
                    console.error('Failed to fetch chatbot AI provider:', e);
                } finally {
                    setChatbotAIProviderFetched(true);
                }
            }

            // Setup defaults for data indexing
            await setupDataIndexingDefaults();

            // Set data fetched and defaults checked after a short delay
            timer = setTimeout(() => {
                setIsDataFetched(true);
                setIsDefaultsChecked(true);
            }, 100);
        };

        initializeDefaults();

        return () => {
            if (timer) {
                clearTimeout(timer);
            }
        };
    }, []);

    /**
     * Validate form
     *
     * @return {boolean}
     */
    const validate = () => {
        const newErrors = {
            indexingModel: !indexingModelId,
            indexingConfig: !indexingConfigId
        };
        setErrors(newErrors);
        return !newErrors.indexingModel && !newErrors.indexingConfig;
    };

    /**
     * Handle regenerate
     */
    const handleRegenerate = () => {
        if (!validate()) {
            return;
        }

        const config = {
            indexing_ai_model_id: indexingModelId,
            indexing_config_id: indexingConfigId
        };

        onRegenerate(config);
    };

    return (
        <PopupContainer
            title={__("Regenerate datasets", 'limb-chatbot')}
            description={__("Select data indexing model and config to regenerate all datasets.", 'limb-chatbot')}
            close={loading ? null : close}
            footer={(
                <>
                    <Button
                        type="secondary"
                        label={__("Cancel", 'limb-chatbot')}
                        onClick={close}
                        disabled={loading}
                    />
                    <Button
                        type="primary"
                        label={__("Regenerate", 'limb-chatbot')}
                        onClick={handleRegenerate}
                        loading={loading}
                        disabled={loading}
                    />
                </>
            )}
        >
            <div className='lbaic-settings-column'>
                <div className='lbaic-settings-column-in'>
                    <Model
                        isDataFetched={isDataFetched && chatbotAIProviderFetched}
                        isDefaultsChecked={isDefaultsChecked}
                        modelId={indexingModelId}
                        setModelId={setIndexingModelId}
                        endpoints={['embeddings']}
                        aiProviderId={chatbotAIProviderId}
                        isAIProviderRequired={true}
                        aiProviderSelected={setIndexingAIProviderId}
                        fieldProps={{
                            validate: (value) => {
                                setErrors(prev => ({...prev, indexingModel: !value}));
                            },
                            errorMessage: errors.indexingModel ? __("This field is required.", 'limb-chatbot') : ''
                        }}
                        autoSelect={true}
                        setLoading={() => {
                        }}
                        notifications={notifications}
                        disabled={loading || !chatbotAIProviderId}
                        placeholder={__("Data indexing model", 'limb-chatbot')}
                    />
                </div>
                <div className='lbaic-settings-column-in'>
                    <Config
                        ref={indexingConfigRef}
                        aiProviderId={chatbotAIProviderId}
                        isDataFetched={isDataFetched && chatbotAIProviderFetched}
                        isDefaultsChecked={isDefaultsChecked}
                        configId={indexingConfigId}
                        setConfigId={setIndexingConfigId}
                        fieldProps={{
                            validate: (value) => {
                                setErrors(prev => ({...prev, indexingConfig: !value}));
                            },
                            errorMessage: errors.indexingConfig ? __("This field is required.", 'limb-chatbot') : ''
                        }}
                        setLoading={() => {
                        }}
                        notifications={notifications}
                        disabled={loading || !indexingModelId || !chatbotAIProviderId}
                    />
                </div>
            </div>
        </PopupContainer>
    );
}
