import {useEffect, useMemo, useRef, useState} from "@wordpress/element";
import {__, sprintf} from "@wordpress/i18n";
import {useSortable} from "@dnd-kit/sortable";
import {CSS} from "@dnd-kit/utilities";
import Input from "../../../../../../../../fields/input";
import Range from "../../../../../../../../fields/range";
import Tooltip from "../../../../../../../../fields/tooltip";
import Dropdown from "../../../../../../../../fields/dropdown";
import Checkbox from "../../../../../../../../fields/checkbox";
import Toggle from "../../../../../../../../fields/toggle";
import BlockEditable from "../../../../../../../../fields/blockeditable";
import Description from "../../../../../../../../sections/description";
import Badge from "../../../../../../../../fields/badge";
import Emoji from "../../../../../../../../button/emoji";
import confirm from "../../../../../../../../../helpers/confirm";
import {required, validate} from "../../../../../../../../../../validations";
import {
    getParameterTypesForDropdown
} from "../../_constants/parameter-types";
import Label from "../../../../../../../../sections/label";
import {getParameterNameValidator} from "../../_utils/validations";
import {generateNameFromLabel} from "../../_utils/name-generation";
import {GetPostTypes} from "../../../../../../../../../rest/wp-objects";
import Notice from "../../../../../../../../sections/notice";
import {GetVectorIndexes} from "../../../../../../../../../rest/vectors-indexes";
import {handleError} from "../../../../../../../../../helpers/notifications";
import {getNavLinkTo} from "../../../../../../../../../helpers";
import LeadFieldMap from "../../../../../../../../fields/specific-fields/lead-field-map";

export default function ParameterItem({
                                          index,
                                          parameter,
                                          moveUp,
                                          moveDown,
                                          update,
                                          remove,
                                          newParameterIds,
                                          notifications,
                                          allParameters = [],
                                          allCallbacks = [],
                                          forceOpen = false,
                                          onValidationRef,
                                          setLoading,
                                          navigate,
                                          onSave
                                      }) {
    const {
        attributes,
        listeners,
        setNodeRef,
        transform,
        transition,
    } = useSortable({id: parameter.id});

    const style = {
        transform: CSS.Transform.toString(transform),
        transition,
    };

    const [opened, setOpened] = useState(newParameterIds?.includes(parameter.id));
    const [labelError, setLabelError] = useState(false);
    const [nameError, setNameError] = useState(false);
    const [postTypes, setPostTypes] = useState([]);
    const [hasRecommendations, setHasRecommendations] = useState(true);
    const [cptError, setCptError] = useState(false);
    const [showLeadCaptureDropdown, setShowLeadCaptureDropdown] = useState(() => {
        return Boolean(parameter.config?.lead_capture_map_field);
    });
    const prevForceOpenRef = useRef(forceOpen);

    const selectedPostTypeLabel = postTypes.find(item => item.value === parameter.config?.cpt)?.label;

    useEffect(() => {
        if (parameter.type === 'vector_search') {
            checkHasRecommendations(parameter.config?.cpt);
        }
    }, []);

    /**
     * Validate CPT field
     *
     * @param {string} value CPT value
     * @return {boolean}
     */
    const validateCpt = (value) => {
        const res = validate(value, [required]);
        setCptError(!res.valid ? res.message : false);
        return res.valid;
    };

    /**
     * Trigger validation for all fields
     */
    const triggerValidation = () => {
        validateLabel(parameter.label || '');
        validateName(parameter.name || '');
        // Validate vector_search specific field: cpt (required)
        if (parameter.type === 'vector_search') {
            validateCpt(parameter.config?.cpt || '');
            // Check recommendations
            checkHasRecommendations(parameter.config?.cpt);
        }
    };

    // Expose validation trigger to parent
    useEffect(() => {
        if (onValidationRef) {
            onValidationRef(triggerValidation);
        }
        return () => {
            if (onValidationRef) {
                onValidationRef(null);
            }
        };
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [onValidationRef]);

    // Open accordion when forceOpen becomes true (allows user to close manually, but reopens on save if errors persist)
    useEffect(() => {
        // Only open when forceOpen transitions from false to true (not when it stays true)
        if (forceOpen && !prevForceOpenRef.current) {
            setOpened(true);
            // Trigger validation when opening due to forceOpen
            triggerValidation();
        }
        prevForceOpenRef.current = forceOpen;
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [forceOpen]);

    // Create parameter types with badges for dropdown
    const parameterTypesWithBadges = useMemo(() => {
        return getParameterTypesForDropdown();
    }, []);

    const handleRemove = async () => {
        if (await confirm(__("Are you sure you want to delete this parameter?", 'limb-chatbot'))) {
            remove(index);
        }
    };

    const updateField = (field, value) => {
        update(index, field, value);
    };

    /**
     * Handle label blur event
     * Auto-generate name from label if name is empty
     *
     * @param {Event} e Blur event
     */
    const handleLabelBlur = (e) => {
        const labelValue = e.target.value || '';
        const currentName = parameter.name || '';

        // Only auto-generate if name is empty (after trim)
        if (!currentName.trim()) {
            const generatedName = generateNameFromLabel(labelValue);
            if (generatedName) {
                updateField('name', generatedName);
                // Trigger validation for the generated name
                validateName(generatedName);
            }
        }
    };

    /**
     * Initialize config for buttons type
     */
    const initializeButtonsConfig = () => {
        if (parameter.type === 'buttons' && (!parameter.config || !parameter.config.options)) {
            updateField('config', {options: []});
        }
    };

    /**
     * Initialize config for vector_search type
     */
    const initializeVectorSearchConfig = () => {
        if (parameter.type === 'vector_search') {
            const initializeConfig = {};
            // CPT
            if ((!parameter.config || !parameter.config.cpt)) {
                initializeConfig.cpt = '';
            }
            // Similarity score
            if ((!parameter.config || !parameter.config.similarity_score)) {
                initializeConfig.similarity_score = 33;
            }
            updateField('config', {...(parameter.config || {}), ...initializeConfig});
        }
    };

    /**
     * Get post types
     *
     * @return {Promise<void>}
     */
    const getPostTypes = async () => {
        try {
            const res = await GetPostTypes();
            setPostTypes(res.map(item => ({
                label: item.name,
                value: item.slug,
                icon: ['post', 'page'].includes(item.slug) ? item.slug : 'settings',
            })));
        } catch (e) {
            // Handle error silently or show notification
        }
    };

    /**
     *
     * @param postType
     * @return {Promise<void>}
     */
    const checkHasRecommendations = async (postType) => {
        if (!postType) {
            setHasRecommendations(true);
            return;
        }
        setLoading(prev => prev + 1);
        try {
            const res = await GetVectorIndexes(LimbChatbot.rest.url, LimbChatbot.rest.nonce, {
                post_type: postType,
                per_page: 1
            });
            setHasRecommendations(res?.total > 0);
        } catch (e) {
            handleError(e);
            setHasRecommendations(false);
        }
        setLoading(prev => prev - 1);
    }

    /**
     * Get buttons options
     */
    const getButtonsOptions = () => {
        if (parameter.type === 'buttons' && parameter.config?.options) {
            return Array.isArray(parameter.config.options) ? parameter.config.options : [];
        }
        return [];
    };

    /**
     * Add new button option
     */
    const addButtonOption = () => {
        const options = getButtonsOptions();
        const newOptions = [
            ...options,
            {label: '', value: '', tooltip: ''}
        ];
        updateField('config', {...parameter.config, options: newOptions});
    };

    /**
     * Remove button option
     *
     * @param {number} optionIndex Option index
     */
    const removeButtonOption = (optionIndex) => {
        const options = getButtonsOptions();
        const newOptions = options.filter((_, i) => i !== optionIndex);
        updateField('config', {...parameter.config, options: newOptions});
    };

    /**
     * Update button option field
     *
     * @param {number} optionIndex Option index
     * @param {string} field Field name (label, value, tooltip)
     * @param {any} value Field value
     */
    const updateButtonOption = (optionIndex, field, value) => {
        const options = getButtonsOptions();
        const newOptions = options.map((item, i) =>
            i === optionIndex ? {...item, [field]: value} : item
        );
        updateField('config', {...parameter.config, options: newOptions});
    };

    const validateLabel = (value) => {
        const res = validate(value, [required]);
        setLabelError(!res.valid ? res.message : false);
        return res.valid;
    };

    const validateName = getParameterNameValidator(setNameError, parameter, allParameters, allCallbacks);

    /**
     * Initialize buttons config on mount or when type changes
     */
    useEffect(() => {
        if (parameter.type === 'buttons') {
            initializeButtonsConfig();
        } else if (parameter.type === 'vector_search') {
            initializeVectorSearchConfig();
        } else {
            // Clear cpt error when switching away from vector_search
            if (cptError) {
                setCptError(false);
            }
        }
    }, [parameter.type]);

    /**
     * Fetch post types on mount
     */
    useEffect(() => {
        if (postTypes.length === 0) {
            getPostTypes();
        }
    }, []);


    /**
     * Get static placeholder based on parameter type and field
     *
     * @param {string} field Field name (label, name, question, placeholder)
     * @return {string} Static placeholder text
     */
    const getStaticPlaceholder = (field) => {
        if (parameter.type === 'text') {
            switch (field) {
                case 'label':
                    return __("e.g., User name", 'limb-chatbot');
                case 'name':
                    return __("e.g., user_name", 'limb-chatbot');
                case 'question':
                    return __("e.g., What's your name?", 'limb-chatbot');
                case 'placeholder':
                    return __("e.g., Enter your name", 'limb-chatbot');
                default:
                    return '';
            }
        } else if (parameter.type === 'textarea') {
            switch (field) {
                case 'label':
                    return __("e.g., Message", 'limb-chatbot');
                case 'name':
                    return __("e.g., message", 'limb-chatbot');
                case 'question':
                    return __("e.g., What's your message?", 'limb-chatbot');
                case 'placeholder':
                    return __("e.g., Enter your message", 'limb-chatbot');
                default:
                    return '';
            }
        } else if (parameter.type === 'email') {
            switch (field) {
                case 'label':
                    return __("e.g., User email", 'limb-chatbot');
                case 'name':
                    return __("e.g., user_email", 'limb-chatbot');
                case 'question':
                    return __("e.g., What's your email address so we can send you updates?", 'limb-chatbot');
                case 'placeholder':
                    return __("e.g., you@example.com", 'limb-chatbot');
                default:
                    return '';
            }
        } else if (parameter.type === 'url') {
            switch (field) {
                case 'label':
                    return __("e.g., Website URL", 'limb-chatbot');
                case 'name':
                    return __("e.g., website_url", 'limb-chatbot');
                case 'question':
                    return __("e.g., What's your website URL?", 'limb-chatbot');
                case 'placeholder':
                    return __("e.g., https://example.com", 'limb-chatbot');
                default:
                    return '';
            }
        } else if (parameter.type === 'vector_search') {
            switch (field) {
                case 'label':
                    return __("e.g., Documentation Search", 'limb-chatbot');
                case 'name':
                    return __("e.g., documentation_search", 'limb-chatbot');
                case 'question':
                    return '';
                case 'placeholder':
                    return '';
                default:
                    return '';
            }
        }
        // Default placeholders for other types
        switch (field) {
            case 'label':
                return __("e.g., Product search", 'limb-chatbot');
            case 'name':
                return __("e.g., search_query", 'limb-chatbot');
            case 'question':
                return '';
            case 'placeholder':
                return __("e.g., Search products", 'limb-chatbot');
            default:
                return '';
        }
    };

    return (
        <div className='lbaic-settings-table-accordion-body' style={style}>
            <div ref={setNodeRef}
                 className={`lbaic-settings-table-accordion-body-in lbaic-settings-table-accordion-summary lbaic-settings-cb-pw-table-summary${opened ? ' active' : ''}`}>
                <div className="lbaic-settings-table-accordion-body-item lbaic-settings-cb-pw-table-actions">
                    <div className="lbaic-settings-cb-pw-table-left-actions-in">
                        <button
                            className="lbaic-settings-cb-pw-button lbaic-settings-cb-pw-button-dragable lbaic-settings-button-reset" {...listeners} {...attributes}>
                            <svg className="lbaic-settings-cb-pw-button-i" xmlns="http://www.w3.org/2000/svg"
                                 fill="none"
                                 viewBox="0 0 24 24">
                                <use href="#lbaic-settings-drag"/>
                            </svg>
                        </button>
                        <div className="lbaic-settings-cb-pw-table-position-actions">
                            <button
                                className="lbaic-settings-cb-pw-button lbaic-settings-button-reset lbaic-settings-cb-pw-table-position-actions-item"
                                onClick={moveUp}>
                                <svg className="lbaic-settings-cb-pw-table-position-actions-i"
                                     xmlns="http://www.w3.org/2000/svg" fill="none"
                                     viewBox="0 0 8 5">
                                    <use href="#lbaic-settings-backward"/>
                                </svg>
                            </button>
                            <button
                                className="lbaic-settings-cb-pw-button lbaic-settings-button-reset lbaic-settings-cb-pw-table-position-actions-item"
                                onClick={moveDown}>
                                <svg className="lbaic-settings-cb-pw-table-position-actions-i"
                                     xmlns="http://www.w3.org/2000/svg" fill="none"
                                     viewBox="0 0 8 5">
                                    <use href="#lbaic-settings-forward"/>
                                </svg>
                            </button>
                        </div>
                    </div>
                </div>
                <div
                    className="lbaic-settings-table-accordion-body-item lbaic-settings-cb-pw-table-actions lbaic-settings-cb-pw-table-number"
                    onClick={() => setOpened(!opened)}>
                    <span
                        className="lbaic-settings-table-accordion-body-label lbaic-settings-cb-pw-table-accordion-body-label">{index + 1}</span>
                </div>
                <div className="lbaic-settings-table-accordion-body-item lbaic-settings-cb-pw-table-body-item"
                     onClick={() => setOpened(!opened)}>
                    <div className="lbaic-settings-actions-pi-table-title-wrapper">
                        <span
                            className={`lbaic-settings-table-accordion-body-label lbaic-settings-cb-pw-table-accordion-body-label${!parameter.label ? ' lbaic-settings-cb-pw-table-card-body-label-null' : ''}`}>
                            {parameter.label || __("no label", 'limb-chatbot')}
                        </span>
                        {Boolean(parameter.required) && (
                            <Badge label={__("Required", 'limb-chatbot')} isSmall={true}
                                   className='lbaic-settings-badge-red'/>
                        )}
                    </div>
                    <button
                        className="lbaic-settings-cb-pw-table-actions-item lbaic-settings-cb-pw-table-actions-edit lbaic-settings-cb-pw-button-primary lbaic-settings-button-reset"
                        onClick={() => setOpened(!opened)}>
                        <svg className="lbaic-settings-cb-pw-table-accordion-body-i"
                             xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                            <use href="#lbaic-settings-edit"/>
                        </svg>
                    </button>
                </div>
                <div className="lbaic-settings-table-accordion-body-item lbaic-settings-cb-pw-table-actions">
                    <div className="lbaic-settings-cb-pw-table-actions-in lbaic-settings-cb-pw-table-actions-nested-in">
                        <button
                            className='lbaic-settings-cb-pw-table-actions-item lbaic-settings-cb-pw-button-primary lbaic-settings-button-reset'
                            onClick={handleRemove}>
                            <svg className="lbaic-settings-cb-pw-table-accordion-body-i"
                                 xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                                <use href="#lbaic-settings-delete"/>
                            </svg>
                        </button>
                    </div>
                </div>
            </div>
            <div
                className={`lbaic-settings-table-accordion-body-in lbaic-settings-table-accordion-details lbaic-settings-cb-pw-table-accordion-details${opened ? ' opened' : ''}`}>
                <div className="lbaic-settings-table-accordion-body-item lbaic-settings-table-accordion-details-in">
                    <div
                        className="lbaic-settings-table-accordion-content lbaic-settings-cb-pw-table-accordion-content">
                        <div className="lbaic-settings-divider-gap-end-inner"/>
                        <div className="lbaic-settings-column">
                            <div className="lbaic-settings-column-in">
                                <Dropdown
                                    value={parameter.type}
                                    setValue={(value) => {
                                        updateField('type', value);
                                        // Initialize config when switching to buttons type
                                        if (value === 'buttons') {
                                            setTimeout(() => initializeButtonsConfig(), 0);
                                        } else if (value === 'vector_search') {
                                            setTimeout(() => initializeVectorSearchConfig(), 0);
                                        }
                                    }}
                                    options={parameterTypesWithBadges}
                                    placeholder={__("Type", 'limb-chatbot')}
                                />
                            </div>
                            <div className="lbaic-settings-column-in lbaic-settings-column-align-end">
                                <Checkbox
                                    isChecked={parameter.required}
                                    toggleValue={() => updateField('required', !parameter.required)}
                                    className='lbaic-settings-checkbox-h-42'
                                    label={__("Required", 'limb-chatbot')}
                                />
                            </div>
                        </div>
                        {parameter.type === 'vector_search' && (
                            <>
                                <div className="lbaic-settings-column">
                                    <div className="lbaic-settings-column-in">
                                        <Dropdown
                                            value={parameter.config?.cpt || ''}
                                            setValue={(value) => {
                                                updateField('config', {...(parameter.config || {}), cpt: value});
                                                validateCpt(value);
                                                // Check vector indexes
                                                checkHasRecommendations(value);
                                            }}
                                            options={postTypes}
                                            placeholder={__("Post type", 'limb-chatbot')}
                                            validate={validateCpt}
                                            errorMessage={cptError}
                                            iconClassName='lbaic-settings-dropdown-kb-icon'
                                        />
                                        <Description>
                                            {__("Select the post type for recommendations", 'limb-chatbot')}
                                        </Description>
                                    </div>
                                    <div className="lbaic-settings-column-in">
                                        <Range
                                            value={parameter.config?.similarity_score}
                                            setValue={(value) => {
                                                updateField('config', {
                                                    ...(parameter.config || {}),
                                                    similarity_score: value
                                                })
                                            }}
                                            label={__("Keyword match strictness", 'limb-chatbot')}
                                            min={20}
                                            max={99}
                                        >
                                            <Tooltip
                                                label={__("Higher values show exact matches only, lower values include broader related products.", 'limb-chatbot')}/>
                                        </Range>
                                    </div>
                                </div>
                                {!hasRecommendations && (
                                    <>
                                        <Notice
                                            type="warning"
                                            dismissible={false}
                                            title={sprintf(__("%s vectors required", 'limb-chatbot'), selectedPostTypeLabel)}
                                            desc={sprintf(__("Generate %s vectors in Knowledge to enable AI-powered matching.", 'limb-chatbot'), selectedPostTypeLabel)}
                                            style={{
                                                '--lbaic-settings-notice-border-color': '#ffc107',
                                                '--lbaic-settings-notice-color': '#856404',
                                                '--lbaic-settings-notice-bg': '#fff3cd',
                                                '--lbaic-settings-notice-border-radius': '10px',
                                                '--lbaic-settings-notice-button-border-radius': '8px'
                                            }}
                                        >
                                            <div className="lbaic-settings-notice-button-wrapper">
                                                <button
                                                    type="button"
                                                    className="lbaic-settings-button"
                                                    onClick={async () => {
                                                        // Autosave action, but don't publish if not published yet
                                                        if (onSave) {
                                                            try {
                                                                await onSave({ autosave: true });
                                                            } catch (e) {
                                                                // Error already handled in onSave
                                                                return;
                                                            }
                                                        }
                                                        navigate(getNavLinkTo('recommendations', '', {
                                                            action: 'add',
                                                            post_type: parameter.config.cpt
                                                        }));
                                                    }}
                                                >
                                                    <span className="lbaic-settings-button-label">{sprintf(__("Set up %s", 'limb-chatbot'), selectedPostTypeLabel)}</span>
                                                </button>
                                            </div>
                                        </Notice>
                                        <div className="lbaic-settings-divider-gap-end"/>
                                    </>
                                )}
                            </>
                        )}
                        <div className="lbaic-settings-column">
                            <div className="lbaic-settings-column-in">
                                <Input
                                    value={parameter.label}
                                    setValue={(value) => updateField('label', value)}
                                    placeholder={__("Label", 'limb-chatbot')}
                                    staticPlaceholder={getStaticPlaceholder('label')}
                                    autofocus
                                    validate={validateLabel}
                                    errorMessage={labelError}
                                    onBlur={handleLabelBlur}
                                />
                            </div>
                            <div className="lbaic-settings-column-in">
                                <Input
                                    value={parameter.name}
                                    setValue={(value) => updateField('name', value)}
                                    placeholder={__("Name", 'limb-chatbot')}
                                    staticPlaceholder={getStaticPlaceholder('name')}
                                    sanitizeValue={(value) => String(value).replace(/\s/g, '_')}
                                    validate={validateName}
                                    errorMessage={nameError}
                                />
                            </div>
                        </div>
                        <div className="lbaic-settings-column">
                            <div className="lbaic-settings-column-in">
                                <BlockEditable
                                    value={parameter.question || ''}
                                    setValue={(value) => updateField('question', value)}
                                    label={__("Question", 'limb-chatbot')}
                                    placeholder={getStaticPlaceholder('question')}
                                    notifications={notifications}
                                    opened={false}
                                    className='lbaic-settings-blockeditable-white'
                                />
                                <Description>
                                    {__("Question asked to the user before collecting this data", 'limb-chatbot')}
                                </Description>
                            </div>
                            <div className="lbaic-settings-column-in">
                                {parameter.type !== 'buttons' && (
                                    <>
                                        <Input
                                            value={parameter.placeholder}
                                            setValue={(value) => updateField('placeholder', value)}
                                            placeholder={__("Placeholder", 'limb-chatbot')}
                                            staticPlaceholder={getStaticPlaceholder('placeholder')}
                                        />
                                        <Description>
                                            {__("Helper text shown inside the input field", 'limb-chatbot')}
                                        </Description>
                                    </>
                                )}
                            </div>
                        </div>
                        {parameter.type === 'buttons' && (
                            <div className="lbaic-settings-column">
                                <div className="lbaic-settings-column-in">
                                    {(() => {
                                        const options = getButtonsOptions();
                                        return (
                                            <div className="lbaic-settings-buttons-options-list">
                                                <Label>{__("Button options", 'limb-chatbot')}</Label>
                                                {options.length > 0 && (
                                                    <div className="lbaic-settings-buttons-options-list-items">
                                                        {options.map((option, optionIndex) => (
                                                            <div key={optionIndex}
                                                                 className="lbaic-settings-buttons-options-row">
                                                                <Input
                                                                    value={option?.label || ''}
                                                                    setValue={(value) => updateButtonOption(optionIndex, 'label', value)}
                                                                    placeholder={__("Label", 'limb-chatbot')}
                                                                    validate={(value) => {
                                                                        if (!value || !String(value).trim()) {
                                                                            return false;
                                                                        }
                                                                        return true;
                                                                    }}
                                                                    actions={[
                                                                        {
                                                                            component: Emoji,
                                                                            props: {
                                                                                chosen: (obj) => {
                                                                                    const currentValue = option?.label || '';
                                                                                    updateButtonOption(optionIndex, 'label', currentValue + obj.emoji);
                                                                                }
                                                                            }
                                                                        }
                                                                    ]}
                                                                />
                                                                <Input
                                                                    value={option?.value || ''}
                                                                    setValue={(value) => updateButtonOption(optionIndex, 'value', value)}
                                                                    placeholder={__("Value", 'limb-chatbot')}
                                                                    validate={(value) => {
                                                                        if (!value || !String(value).trim()) {
                                                                            return false;
                                                                        }
                                                                        return true;
                                                                    }}
                                                                />
                                                                <Input
                                                                    value={option?.tooltip || ''}
                                                                    setValue={(value) => updateButtonOption(optionIndex, 'tooltip', value)}
                                                                    placeholder={__("Tooltip", 'limb-chatbot')}
                                                                />
                                                                <button
                                                                    type="button"
                                                                    className="lbaic-settings-button-reset lbaic-settings-buttons-options-remove"
                                                                    onClick={() => removeButtonOption(optionIndex)}
                                                                >
                                                                    <svg
                                                                        className="lbaic-settings-buttons-options-remove-i"
                                                                        xmlns="http://www.w3.org/2000/svg"
                                                                        fill="none" viewBox="0 0 24 24">
                                                                        <use href="#lbaic-settings-close"/>
                                                                    </svg>
                                                                </button>
                                                            </div>
                                                        ))}
                                                    </div>
                                                )}
                                                <div className="lbaic-settings-http-kv-actions">
                                                    <button
                                                        type="button"
                                                        className="lbaic-settings-button lbaic-settings-button-center lbaic-settings-button-h-40 lbaic-settings-button-primary"
                                                        onClick={addButtonOption}
                                                    >
                                                        <span className="lbaic-settings-button-label">
                                                            {__("+ Add option", 'limb-chatbot')}
                                                        </span>
                                                    </button>
                                                    <Description>
                                                        {__("Label is what users see (e.g., \"M\"), Value is what gets stored (e.g., \"medium\")", 'limb-chatbot')}
                                                    </Description>
                                                </div>
                                            </div>
                                        );
                                    })()}
                                </div>
                            </div>
                        )}
                        <div className="lbaic-settings-column">
                            <div className="lbaic-settings-column-in">
                                <Toggle
                                    isActive={showLeadCaptureDropdown}
                                    onClick={() => {
                                        const newValue = !showLeadCaptureDropdown;
                                        setShowLeadCaptureDropdown(newValue);
                                        if (!newValue) {
                                            updateField('lead_capture_map_field', '');
                                        }
                                    }}
                                    label={__("Lead capture field", 'limb-chatbot')}
                                />
                                <Description>{__("Mark this field as a lead capture field", 'limb-chatbot')}</Description>
                            </div>
                            <div className="lbaic-settings-column-in">
                                {showLeadCaptureDropdown && (
                                    <>
                                        <LeadFieldMap
                                            value={parameter.config?.lead_capture_map_field ?? ''}
                                            setValue={(value) => updateField('lead_capture_map_field', value)}
                                            placeholder={__("Map to Leads column", 'limb-chatbot')}
                                            notifications={notifications}
                                        />
                                        <Description>{__("Select which Leads table column to map this field to.", 'limb-chatbot')}</Description>
                                    </>
                                )}
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    );
}