import {useEffect, useState} from "@wordpress/element";
import {__, sprintf} from "@wordpress/i18n";
import Container from "../../../containers/content/container";
import TabSettings from "../../../../components/tab-settings";
import {handleError} from "../../../../../../helpers/notifications";
import {validate} from "../../../../../../../validations";
import useSettingsErrorsState from "../../../../components/hooks/settings-errors-state";
import Toggle from "../../../../../fields/toggle";
import Tooltip from "../../../../../fields/tooltip";
import {chunkArray} from "../../../../../../../helpers";

// Constants
const TAB_NAME = 'settings.knowledge.automation';
const POST_TYPES = LimbChatbot?.wp_objects?.post_types || [];
const AUTO_VECTOR_KEY_PREFIX = 'auto_sync_for_post_';

export default function KnowledgeAutoSync({notifications}) {
    const [loading, setLoading] = useState(0);
    const [isDataFetched, setIsDataFetched] = useState(false);
    const [showContent, setShowContent] = useState(false);
    // Settings
    const settings = POST_TYPES.reduce((acc, item) => {
        acc[AUTO_VECTOR_KEY_PREFIX + item.slug] = useState(false);
        return acc;
    }, {});
    const errors = POST_TYPES.reduce((acc, item) => {
        acc[AUTO_VECTOR_KEY_PREFIX + item.slug] = useState(false);
        return acc;
    }, {});

    /**
     * Validate field
     *
     * @param {string} name Field name
     * @param {any} value Field value
     * @return {boolean}
     */
    const validateField = (name, value) => {
        try {
            if (!name.includes(AUTO_VECTOR_KEY_PREFIX)) {
                handleError({
                    message: "Field validation failed, field name is invalid.",
                    data: {
                        name,
                        value,
                    }
                }, notifications.set, {
                    title: __("Field validation failed.", 'limb-chatbot'),
                    description: __("Field name is invalid.", 'limb-chatbot'),
                });

                return false;
            }
            // Validate field
            let validations = [];

            const res = validate(value, validations);
            // Update field errors state
            errors[name][1](!res.valid ? res.message : false);

            return res.valid;
        } catch (e) {
            handleError(e, notifications.set, {
                title: __("Field validation failed.", 'limb-chatbot'),
                description: e.message ? __(e.message, 'limb-chatbot') : __("Something went wrong.", 'limb-chatbot'),
            });
            return false;
        }
    }

    useSettingsErrorsState({
        settings,
        errors,
        title: __("Knowledge Sources Settings", 'limb-chatbot'),
        validateField,
        isDataFetched,
    });

    useEffect(() => {
        if (!showContent) {
            if (
                !loading
                && isDataFetched
            ) {
                setTimeout(() => setShowContent(true), 200);
            }
        }
    }, [loading, isDataFetched]);

    return <>
        <TabSettings
            name={TAB_NAME}
            settings={settings}
            keysPrefix='lbaic.utilities.chatbot'
            validateField={validateField}
            tabLoading={loading}
            contentLoading={!showContent}
            dataFetched={value => setIsDataFetched(value)}
            notifications={notifications}
        >
            <Container>
                {chunkArray(POST_TYPES, 2, true).map((chunk, i) => (
                    <div
                        key={'chunk' + i}
                        className="lbaic-settings-column lbaic-settings-column-h-42"
                    >
                        {chunk.map((item, j) => {
                            if (!item?.slug) {
                                return (
                                    <div key={'item' + j} className="lbaic-settings-column-in"/>
                                );
                            }
                            // Settings keys
                            const autoVectorKey = AUTO_VECTOR_KEY_PREFIX + item.slug;

                            return (
                                <div className="lbaic-settings-column-in">
                                    <Toggle
                                        label={sprintf(__("Auto-sync %s", 'limb-chatbot'), item.name)}
                                        isActive={settings[autoVectorKey][0]}
                                        onClick={() => settings[autoVectorKey][1](!settings[autoVectorKey][0])}
                                    >
                                        <Tooltip
                                            label={sprintf(__("Automatically sync newly published %s.", 'limb-chatbot'), item.name)}
                                            width={160}
                                        />
                                    </Toggle>
                                </div>
                            );
                        })}
                    </div>
                ))}
            </Container>
        </TabSettings>
    </>
}