import {useState, useRef, useEffect, useMemo, useImperativeHandle, forwardRef} from "@wordpress/element";
import {__} from "@wordpress/i18n";
import Input from "../../../../../../../../../../fields/input";
import LexicalEditor from "../../../../../../../../../../fields/lexical";
import Description from "../../../../../../../../../../sections/description";
import Checkbox from "../../../../../../../../../../fields/checkbox";
import Toggle from "../../../../../../../../../../fields/toggle";
import BlockEditable from "../../../../../../../../../../fields/blockeditable";
import Config from "../../../../../../../../../../fields/specific-fields/config";
import AddEditConfig from "../../../../../../../../../../popups/ai-providers/models/add-edit-config";
import SlackChannel from "./channel";
import {getRequiredValidator, getCallbackNameValidator} from "../../../../_utils/validations";
import {useAvailableVariables} from "../../../../_utils/variables";
import InsertVariable from "../../../../../../../../../../button/insert-variable";

const SlackConfiguration = forwardRef(({
                                           callback,
                                           updateField,
                                           notifications,
                                           allParameters = [],
                                           allCallbacks = [],
                                           validationRef
                                       }, ref) => {
    const [loading, setLoading] = useState(0);
    const [nameError, setNameError] = useState(false);
    const [titleError, setTitleError] = useState(false);
    const [configIdError, setConfigIdError] = useState(false);
    const [contentError, setContentError] = useState(false);
    const [showConfigPopup, setShowConfigPopup] = useState(false);
    const configRef = useRef(null);

    // Create validators
    const validateName = getCallbackNameValidator(setNameError, callback, allParameters, allCallbacks);
    const validateTitle = getRequiredValidator(setTitleError);
    const validateConfigId = getRequiredValidator(setConfigIdError);
    const validateContent = getRequiredValidator(setContentError);

    /**
     * Trigger validation for all fields
     */
    const triggerValidation = () => {
        validateName(callback?.name || '');
        validateTitle(callback?.title || '');
        validateConfigId(callback?.config?.config_id || '');
        validateContent(callback?.config?.content || '');
    };

    // Expose validation trigger via ref
    useImperativeHandle(ref, () => ({
        triggerValidation
    }));

    // Also expose via validationRef if provided (for backward compatibility)
    useEffect(() => {
        if (validationRef) {
            validationRef.current = {
                triggerValidation
            };
        }
        return () => {
            if (validationRef) {
                validationRef.current = null;
            }
        };
    }, [validationRef, callback]);

    // Calculate available variables for insert variable menu
    const availableVariables = useAvailableVariables(callback, allParameters, allCallbacks);

    // Check if there are any variables available
    const hasVariables = useMemo(() => {
        // Check if parameters group has items
        if (availableVariables?.parameters?.items && Array.isArray(availableVariables.parameters.items)) {
            return availableVariables.parameters.items.length > 0;
        }
        return false;
    }, [availableVariables]);

    /**
     * Handle config selected
     */
    const handleConfigSelected = (config) => {
        if (config?.id) {
            updateField('config_id', config.id);
        }
    };

    /**
     * Handle config added
     */
    const handleConfigAdded = (newConfig) => {
        // Use Config component's ref to add the new config
        if (configRef.current?.newConfigAdded) {
            configRef.current.newConfigAdded(newConfig);
        }
        setShowConfigPopup(false);
    };

    /**
     * Handle config updated
     */
    const handleConfigUpdated = (updatedConfig) => {
        setShowConfigPopup(false);
    };

    /**
     * Handle config deleted
     */
    const handleConfigDeleted = (deletedId) => {
        // Clear config_id if it was deleted
        if (callback?.config?.config_id === deletedId) {
            updateField('config_id', null);
        }
        setShowConfigPopup(false);
    };

    /**
     * Open add config popup
     */
    const handleAddConfig = () => {
        setShowConfigPopup(true);
    };

    /**
     * Update config_id in config
     */
    const updateConfigId = (configId) => {
        const id = configId ? parseInt(configId) : null;
        updateField('config_id', id);
    };

    /**
     * Update content in config
     */
    const updateContent = (value) => {
        updateField('content', value);
    };

    return (
        <>
            <div className="lbaic-settings-column">
                <div className="lbaic-settings-column-in">
                    <Input
                        value={callback?.name || ''}
                        setValue={(value) => updateField('name', value)}
                        placeholder={__("Handler name", 'limb-chatbot')}
                        validate={validateName}
                        errorMessage={nameError}
                        autofocus
                    />
                </div>
                <div className="lbaic-settings-column-in">
                    <Checkbox
                        isChecked={Boolean(callback?.is_required)}
                        toggleValue={() => updateField('is_required', callback?.is_required ? 0 : 1)}
                        label={__("Required", 'limb-chatbot')}
                        className='lbaic-settings-checkbox-h-42'
                    />
                </div>
            </div>
            <div className="lbaic-settings-column">
                <div className="lbaic-settings-column-in">
                    <Input
                        value={callback?.title || ''}
                        setValue={(value) => updateField('title', value)}
                        placeholder={__("Title", 'limb-chatbot')}
                        staticPlaceholder={__("e.g., New Voucher code was requested", 'limb-chatbot')}
                        validate={validateTitle}
                        errorMessage={titleError}
                    />
                    <Description>
                        {__("A descriptive title for this Slack notification.", 'limb-chatbot')}
                    </Description>
                </div>
            </div>
            <div className="lbaic-settings-column">
                <div className="lbaic-settings-column-in">
                    <Config
                        ref={configRef}
                        aiProviderId="slack"
                        isDataFetched={true}
                        isDefaultsChecked={true}
                        configId={callback?.config?.config_id || ''}
                        setConfigId={updateConfigId}
                        setLoading={setLoading}
                        configSelected={handleConfigSelected}
                        fieldProps={{
                            addNew: handleAddConfig,
                            validate: validateConfigId,
                            errorMessage: configIdError,
                        }}
                        notifications={notifications}
                    />
                    <Description>
                        {__("Select a Slack API configuration. Use 'Add new' to create a new configuration.", 'limb-chatbot')}
                    </Description>
                </div>
            </div>
            <SlackChannel
                callback={callback}
                updateField={updateField}
                notifications={notifications}
            />
            <div className="lbaic-settings-column">
                <div className="lbaic-settings-column-in">
                    <LexicalEditor
                        value={callback?.config?.content || ''}
                        setValue={updateContent}
                        placeholder={__("🛒 *New Voucher Code was requested*", 'limb-chatbot')}
                        validate={validateContent}
                        errorMessage={contentError}
                        disabled={false}
                        extraActions={[
                            {
                                component: InsertVariable,
                                props: {
                                    variables: availableVariables,
                                    chosen: (variable, insertVariable) => {
                                        // Use insertVariable method if available (preserves whitespace and triggers validation)
                                        if (insertVariable) {
                                            insertVariable(variable);
                                        } else {
                                            // Fallback to old method
                                            const currentValue = callback?.config?.content || '';
                                            const newValue = currentValue + variable;
                                            updateField('content', newValue);
                                            // Trigger validation after inserting variable
                                            getRequiredValidator(setContentError)(newValue);
                                        }
                                    }
                                },
                            }
                        ]}
                    />
                    <Description>
                        {__("Message content with Slack markdown formatting. Use variables from parameters or previous handlers.", 'limb-chatbot')}
                    </Description>
                </div>
            </div>
            <div className="lbaic-settings-column">
                <div className="lbaic-settings-column-in">
                    <BlockEditable
                        value={callback?.config?.success_message || ''}
                        setValue={(value) => updateField('success_message', value)}
                        label={__("Success message", 'limb-chatbot')}
                        placeholder={__("Enter success message...", 'limb-chatbot')}
                        className='lbaic-settings-blockeditable-white'
                        notifications={notifications}
                        opened={false}
                        emoji={true}
                        extraActions={[
                            {
                                component: InsertVariable,
                                props: {
                                    variables: availableVariables,
                                    chosen: (variable, insertVariable) => {
                                        // Use insertVariable method if available (preserves cursor position and whitespace)
                                        if (insertVariable) {
                                            insertVariable(variable);
                                        } else {
                                            // Fallback to old method
                                            const currentValue = callback?.config?.success_message || '';
                                            const newValue = currentValue + variable;
                                            updateField('success_message', newValue);
                                        }
                                    },
                                    disabled: !hasVariables
                                },
                            }
                        ]}
                    />
                    <Description>
                        {__("Message to display when this callback completes successfully.", 'limb-chatbot')}
                    </Description>
                </div>
            </div>
            <div className="lbaic-settings-column">
                <div className="lbaic-settings-column-in">
                    <Toggle
                        label={__("Show collected data", 'limb-chatbot')}
                        isActive={callback?.config?.show_collected_data !== false && callback?.config?.show_collected_data !== 0}
                        onClick={() => {
                            const currentValue = callback?.config?.show_collected_data;
                            const isCurrentlyEnabled = currentValue !== false && currentValue !== 0;
                            updateField('show_collected_data', !isCurrentlyEnabled);
                        }}
                    />
                    <Description>
                        {__("Display the collected action parameters in the success message.", 'limb-chatbot')}
                    </Description>
                </div>
                <div className="lbaic-settings-column-in"/>
            </div>
            {showConfigPopup && (
                <AddEditConfig
                    aiProviderId="slack"
                    added={handleConfigAdded}
                    updated={handleConfigUpdated}
                    deleted={handleConfigDeleted}
                    close={() => {
                        setShowConfigPopup(false);
                    }}
                    notifications={notifications}
                    showMakeDefault={false}
                />
            )}
        </>
    );
});

SlackConfiguration.displayName = 'SlackConfiguration';

export default SlackConfiguration;