import {useState, useMemo, useEffect, useImperativeHandle, forwardRef} from "@wordpress/element";
import {__} from "@wordpress/i18n";
import Input from "../../../../../../../../../../fields/input";
import LexicalEditor from "../../../../../../../../../../fields/lexical";
import Checkbox from "../../../../../../../../../../fields/checkbox";
import Toggle from "../../../../../../../../../../fields/toggle";
import BlockEditable from "../../../../../../../../../../fields/blockeditable";
import Description from "../../../../../../../../../../sections/description";
import {
    getRequiredValidator,
    getCallbackNameValidator,
    getEmailValidator,
    getOptionalEmailValidator
} from "../../../../_utils/validations";
import {useAvailableVariables} from "../../../../_utils/variables";
import InsertVariable from "../../../../../../../../../../button/insert-variable";

const EmailConfiguration = forwardRef(({
                                           callback,
                                           updateField,
                                           notifications,
                                           allParameters = [],
                                           allCallbacks = [],
                                           validationRef
                                       }, ref) => {
    const [nameError, setNameError] = useState(false);
    const [toError, setToError] = useState(false);
    const [subjectError, setSubjectError] = useState(false);
    const [messageError, setMessageError] = useState(false);
    const [replyToError, setReplyToError] = useState(false);

    // Create validators
    const validateName = getCallbackNameValidator(setNameError, callback, allParameters, allCallbacks);
    const validateTo = getEmailValidator(setToError);
    const validateSubject = getRequiredValidator(setSubjectError);
    const validateMessage = getRequiredValidator(setMessageError);
    const validateReplyTo = getOptionalEmailValidator(setReplyToError);

    /**
     * Trigger validation for all fields
     */
    const triggerValidation = () => {
        validateName(callback?.name || '');
        validateTo(callback?.config?.to || '');
        validateSubject(callback?.config?.subject || '');
        validateMessage(callback?.config?.body_text || '');
        validateReplyTo(callback?.config?.reply_to || '');
    };

    // 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 (all parameters)
    const availableVariables = useAvailableVariables(callback, allParameters, allCallbacks);

    // Calculate available variables filtered to email type only
    const emailVariables = useAvailableVariables(callback, allParameters, allCallbacks, 'email');

    // 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]);

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

    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')}
                        sanitizeValue={(value) => String(value).replace(/\s/g, '_')}
                        validate={validateName}
                        errorMessage={nameError}
                        autofocus
                    />
                </div>
                <div className="lbaic-settings-column-in">
                    <Checkbox
                        isChecked={callback?.is_required === 1 || callback?.is_required === true}
                        toggleValue={() => updateField('is_required', callback?.is_required === 1 || callback?.is_required === true ? 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?.config?.to || ''}
                        setValue={(value) => updateField('to', value)}
                        placeholder={__("To", 'limb-chatbot')}
                        staticPlaceholder={__("recipient@example.com or {email}", 'limb-chatbot')}
                        validate={validateTo}
                        errorMessage={toError}
                        extraActions={[
                            {
                                component: InsertVariable,
                                props: {
                                    variables: emailVariables,
                                    chosen: variable => {
                                        const newValue = `${callback?.config?.to || ''}${variable}`;
                                        updateField('to', newValue);
                                        // Trigger validation after inserting variable
                                        getEmailValidator(setToError)(newValue);
                                    },
                                    disabled: !hasEmailVariables
                                },
                            }
                        ]}
                    />
                </div>
            </div>
            <div className="lbaic-settings-column">
                <div className="lbaic-settings-column-in">
                    <Input
                        value={callback?.config?.subject || ''}
                        setValue={(value) => updateField('subject', value)}
                        placeholder={__("Subject", 'limb-chatbot')}
                        staticPlaceholder={__("Enter email subject", 'limb-chatbot')}
                        validate={validateSubject}
                        errorMessage={subjectError}
                        extraActions={[
                            {
                                component: InsertVariable,
                                props: {
                                    variables: availableVariables,
                                    chosen: variable => {
                                        const newValue = `${callback?.config?.subject || ''}${variable}`;
                                        updateField('subject', newValue);
                                        // Trigger validation after inserting variable
                                        getRequiredValidator(setSubjectError)(newValue);
                                    },
                                    disabled: !hasVariables
                                },
                            }
                        ]}
                    />
                </div>
            </div>
            <div className="lbaic-settings-column">
                <div className="lbaic-settings-column-in">
                    <LexicalEditor
                        value={callback?.config?.body_text || ''}
                        setValue={(value) => {
                            updateField('body_text', value);
                        }}
                        placeholder={__("Enter your email message...", 'limb-chatbot')}
                        validate={validateMessage}
                        errorMessage={messageError}
                        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?.body_text || '';
                                            const newValue = currentValue + variable;
                                            updateField('body_text', newValue);
                                            // Trigger validation after inserting variable
                                            getRequiredValidator(setMessageError)(newValue);
                                        }
                                    },
                                    disabled: !hasVariables
                                },
                            }
                        ]}
                    />
                </div>
            </div>
            <div className="lbaic-settings-column">
                <div className="lbaic-settings-column-in">
                    <Input
                        value={callback?.config?.reply_to || ''}
                        setValue={(value) => updateField('reply_to', value)}
                        placeholder={__("Reply-To", 'limb-chatbot')}
                        staticPlaceholder={__("reply@example.com (optional)", 'limb-chatbot')}
                        validate={validateReplyTo}
                        errorMessage={replyToError}
                        extraActions={[
                            {
                                component: InsertVariable,
                                props: {
                                    variables: emailVariables,
                                    chosen: variable => {
                                        const newValue = `${callback?.config?.reply_to || ''}${variable}`;
                                        updateField('reply_to', newValue);
                                        // Trigger validation after inserting variable
                                        getOptionalEmailValidator(setReplyToError)(newValue);
                                    },
                                    disabled: !hasEmailVariables
                                },
                            }
                        ]}
                    />
                </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>
        </>
    );
});

EmailConfiguration.displayName = 'EmailConfiguration';

export default EmailConfiguration;