import {useEffect, useRef, useState} from "@wordpress/element";
import {__, sprintf} from "@wordpress/i18n";
import Toggle from "../../../../../../fields/toggle";
import Dropdown from "../../../../../../fields/dropdown";
import MultiSelect from "../../../../../../fields/multiselect";
import Config from "../../../../../../fields/specific-fields/config";
import Button from "../../../../../../button/_";
import Container from "../../../../containers/content/container";
import TabSettings from "../../../../../components/tab-settings";
import Description from "../../../../../../sections/description";
import Notice from "../../../../../../sections/notice";
import Tooltip from "../../../../../../fields/tooltip";
import AddEditConfig from "../../../../../../popups/ai-providers/models/add-edit-config";
import PopupContainer from "../../../../../../popups/container";
import {GetConfig} from "../../../../../../../rest/configs";
import {GetLiveAgents} from "../../../../../../../rest/live-agents";
import {GetSlackAgents, CreateSlackAgents, GetTelegramUsers, GetTelegramAgents, CreateTelegramAgents, RefreshTelegramUsers} from "../../../../../../../rest/integrations";
import {handleError, handleSuccess} from "../../../../../../../helpers/notifications";
import {getInitialData, getProviderFromConfigRelation} from "../../../../../../../helpers";
import {required, validate} from "../../../../../../../../validations";
import useSettingsErrorsState from "../../../../../components/hooks/settings-errors-state";

// Constants
const TAB_NAME = 'settings.chatbot.live-agent';
const SETTINGS_KEYS_PREFIX = 'lbaic.utilities.chatbot';

// Unified fetch method options (same for all integrations)
const FETCH_METHODS = [
    {
        label: __("Polling", 'limb-chatbot'),
        value: 'polling',
    },
    {
        label: __("Event Subscription", 'limb-chatbot'),
        value: 'event_subscription',
    },
];

// Available integrations (can be expanded in the future)
const INTEGRATIONS = [
    {
        label: __("Slack", 'limb-chatbot'),
        value: 'slack',
        icon: 'integration-slack'
    },
    {
        label: __("Telegram", 'limb-chatbot'),
        value: 'telegram',
        icon: 'integration-telegram'
    },
];


export default function LiveAgent({notifications}) {
    // Actions states
    const [loading, setLoading] = useState(0);
    const [isDataFetched, setIsDataFetched] = useState(false);
    const [showAddNewConfigPopup, setShowAddNewConfigPopup] = useState(false);

    // Integration selection (local state, not saved)
    const [selectedIntegration, setSelectedIntegration] = useState('');
    const initialSelectedIntegrationRef = useRef('');

    // Config component ref
    const configRef = useRef(null);
    const [isConfigFetched, setIsConfigFetched] = useState(false);

    // Live agents states (WP users)
    const [agents, setAgents] = useState([]);
    const [loadingAgents, setLoadingAgents] = useState(false);
    const [isAgentsFetched, setIsAgentsFetched] = useState(false);

    // Add agents popup states
    const [showAddAgentsPopup, setShowAddAgentsPopup] = useState(false);
    const [slackAgents, setSlackAgents] = useState([]);
    const [loadingSlackAgents, setLoadingSlackAgents] = useState(false);
    const [selectedSlackAgents, setSelectedSlackAgents] = useState([]);
    const [creatingAgents, setCreatingAgents] = useState(false);

    // Telegram agents popup states
    const [showAddTelegramAgentsPopup, setShowAddTelegramAgentsPopup] = useState(false);
    const [telegramAgents, setTelegramAgents] = useState([]);
    const [loadingTelegramAgents, setLoadingTelegramAgents] = useState(false);
    const [selectedTelegramAgents, setSelectedTelegramAgents] = useState([]);
    const [creatingTelegramAgents, setCreatingTelegramAgents] = useState(false);

    // Telegram users states
    const [telegramUsers, setTelegramUsers] = useState([]);
    const [loadingTelegramUsers, setLoadingTelegramUsers] = useState(false);
    const [isTelegramUsersFetched, setIsTelegramUsersFetched] = useState(false);
    const isRefreshingTelegramUsersRef = useRef(false);

    // Track previous config id
    const previousConfigIdRef = useRef(null);
    // Track previous telegram config id separately (for agents, not just users)
    const previousTelegramAgentsConfigIdRef = useRef(null);
    // Track previous telegram config id for users
    const previousTelegramConfigIdRef = useRef(null);
    // Track if we're in the middle of an integration switch (to prevent stale fetches)
    const isIntegrationSwitchingRef = useRef(false);
    // Track if initial config load happened
    const initialConfigLoadedRef = useRef(false);
    // Track previous integration to detect switches
    const previousIntegrationRef = useRef(null);

    // Settings
    const settings = {
        'live_agent': useState(false),
        'live_agent_config_id': useState(''),
        'agent_ids': useState([]),
        'agent_fetch_method': useState('polling'),
    };

    // Errors
    const errors = {
        'live_agent': useState(false),
        'live_agent_config_id': useState(false),
        'agent_ids': useState(false),
        'agent_fetch_method': useState(false),
    };

    // Ref to access initial data from TabSettings
    const initialDataRef = useRef(getInitialData(settings));

    /**
     * Normalize agent IDs to ensure they're always numbers.
     * This ensures consistent comparison with agentOptions values.
     */
    useEffect(() => {
        if (!isDataFetched) return;

        // Normalize agent_ids
        const agentIds = settings['agent_ids'][0];
        if (Array.isArray(agentIds) && agentIds.length > 0) {
            const normalized = agentIds.map(id => typeof id === 'string' ? parseInt(id, 10) : id);
            if (JSON.stringify(normalized) !== JSON.stringify(agentIds)) {
                settings['agent_ids'][1](normalized);
            }
        }
    }, [isDataFetched, settings['agent_ids'][0]]);

    /**
     * Validate field
     *
     * @param {string} name Field name
     * @param {any} value Field value
     * @return {boolean}
     */
    const validateField = (name, value) => {
        try {
            let validations = [];

            // Only validate when live_agent is enabled
            if (settings['live_agent'][0]) {
                switch (name) {
                    case 'live_agent_config_id':
                    case 'agent_ids':
                    case 'agent_fetch_method':
                        validations = [required];
                        break;
                    default:
                        break;
                }
            }

            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: __("Live agent", 'limb-chatbot'),
        validateField,
        isDataFetched,
    });

    // Clear errors and reset settings to the initial state when live_agent is disabled
    useEffect(() => {
        if (!isDataFetched) {
            return;
        }

        if (!settings['live_agent'][0]) {
            // Clear errors
            errors['live_agent_config_id'][1](false);
            errors['agent_ids'][1](false);
            errors['agent_fetch_method'][1](false);

            // Reset settings to the initial state if initialDataRef is available
            if (initialDataRef.current && isDataFetched) {
                const initialData = initialDataRef.current;

                // Update settings to initial state
                for (const initialDataKey in initialData) {
                    if (initialDataKey === 'live_agent') {
                        continue;
                    }
                    if (initialData.hasOwnProperty(initialDataKey)) {
                        const initialValue = initialData[initialDataKey];
                        settings[initialDataKey][1](initialValue);
                    }
                }
                // Update selected integration to initial state
                setSelectedIntegration(initialSelectedIntegrationRef.current);
            }
        }
    }, [isDataFetched, settings['live_agent'][0]]);

    // Filter out integration-specific settings when saving
    // IMPORTANT: We DON'T actually exclude settings - we preserve all integration data
    // This allows switching between integrations without losing data
    useEffect(() => {
        const filterName = 'lbaic/admin/page/settings/live-agent/dataToUpdate';

        const filterCallback = (data, name) => {
            if (name !== TAB_NAME) {
                return data;
            }

            // Don't filter out any settings - preserve all integration data
            return data;
        };

        // Filter for preview data (handles .preview suffix)
        const previewFilterCallback = (data, name) => {
            if (name !== TAB_NAME) {
                return data;
            }

            // Don't filter out any preview settings either
            return data;
        };

        LimbChatbot.Hooks.addFilter('lbaic.admin.page.settings.dataToUpdate', filterName, filterCallback, 10);
        LimbChatbot.Hooks.addFilter('lbaic.admin.page.settings.preview.dataToUpdate', filterName, previewFilterCallback, 10);

        return () => {
            LimbChatbot.Hooks.removeFilter('lbaic.admin.page.settings.dataToUpdate', filterName);
            LimbChatbot.Hooks.removeFilter('lbaic.admin.page.settings.preview.dataToUpdate', filterName);
        };
    }, [selectedIntegration]);

    // Clear config and data when switching integrations
    useEffect(() => {
        const prevIntegration = previousIntegrationRef.current;

        // Only act after initial load and when switching to a different integration
        if (prevIntegration && selectedIntegration && prevIntegration !== selectedIntegration) {
            // Mark that we're in the middle of an integration switch
            isIntegrationSwitchingRef.current = true;

            // Clear config ID since it belongs to a different integration
            settings['live_agent_config_id'][1]('');

            // Clear agent settings when switching integrations
            settings['agent_ids'][1]([]);
            settings['agent_fetch_method'][1]('polling');

            // Reset agents data
            setAgents([]);
            setIsAgentsFetched(false);
            previousConfigIdRef.current = null;

            // Reset Telegram-specific data
            if (prevIntegration === 'telegram' || selectedIntegration === 'telegram') {
                setTelegramUsers([]);
                previousTelegramConfigIdRef.current = null;
                previousTelegramAgentsConfigIdRef.current = null;
            }

            // Reset config fetched state
            setIsConfigFetched(false);
        }

        previousIntegrationRef.current = selectedIntegration;
    }, [selectedIntegration]);

    const isConfigSelected = !!settings['live_agent_config_id'][0];
    const isSlackIntegration = selectedIntegration === 'slack';
    const isTelegramIntegration = selectedIntegration === 'telegram';

    // Content loading state (latch pattern - once true, stays true)
    const [showContent, setShowContent] = useState(false);
    useEffect(() => {
        if (showContent || !isDataFetched) return;

        // Show content when: live_agent is disabled OR (integration is set AND config is fetched)
        if (!settings['live_agent'][0] || (selectedIntegration && isConfigFetched)) {
            setShowContent(true);
        }
    }, [isDataFetched, settings['live_agent'][0], selectedIntegration, isConfigFetched]);

    const isSelectedIntegrationInitialChecked = useRef(false);

    // Determine integration from saved config or auto-select Slack
    useEffect(() => {
        const determineIntegration = async () => {
            if (!isDataFetched || selectedIntegration) {
                return;
            }

            if (!settings['live_agent'][0]) {
                setSelectedIntegration('');
                return;
            }

            const savedConfigId = settings['live_agent_config_id'][0];
            let foundIntegration = '';
            if (savedConfigId) {
                // Fetch saved config to determine integration
                try {
                    setLoading(prev => prev + 1);
                    const config = await GetConfig(LimbChatbot.rest.url, LimbChatbot.rest.nonce, savedConfigId);
                    if (config?.id) {
                        const integration = getProviderFromConfigRelation(config.related_to);
                        if (integration) {
                            foundIntegration = integration;
                        } else {
                            // Fallback to Slack if integration not found
                            foundIntegration = 'slack';
                        }
                    } else {
                        // Config not found, auto-select Slack
                        foundIntegration = 'slack';
                    }
                } catch (e) {
                    // Error fetching config, auto-select Slack
                    foundIntegration = 'slack';
                } finally {
                    setLoading(prev => prev - 1);
                }
            } else if (settings['live_agent'][0]) {
                // No saved config but live_agent is enabled, auto-select Slack
                foundIntegration = 'slack';
            }

            setSelectedIntegration(foundIntegration);
            // Setup initial integration
            if (!isSelectedIntegrationInitialChecked.current) {
                initialSelectedIntegrationRef.current = foundIntegration;
                isSelectedIntegrationInitialChecked.current = true;
            }
        };
        determineIntegration();
    }, [isDataFetched, settings['live_agent'][0], settings['live_agent_config_id'][0]]);

    // Fetch agents when config changes (for Slack)
    useEffect(() => {
        const configId = settings['live_agent_config_id'][0];
        const configIdChanged = previousConfigIdRef.current !== configId;

        if (configId && configIdChanged && isSlackIntegration) {
            // Fetch new data
            fetchAgents(configId);
            previousConfigIdRef.current = configId;
        } else if (!configId) {
            // Clear agents if no config is selected
            setAgents([]);
            setIsAgentsFetched(true);
            previousConfigIdRef.current = null;
        }
    }, [settings['live_agent_config_id'][0], isSlackIntegration]);

    // Fetch agents when config changes (for Telegram)
    useEffect(() => {
        const configId = settings['live_agent_config_id'][0];
        const configIdChanged = previousTelegramAgentsConfigIdRef.current !== configId;

        if (configId && configIdChanged && isTelegramIntegration) {
            // Fetch new data
            fetchAgents(configId);
            previousTelegramAgentsConfigIdRef.current = configId;
        } else if (!configId && isTelegramIntegration) {
            // Clear agents if no config is selected
            setAgents([]);
            setIsAgentsFetched(true);
            previousTelegramAgentsConfigIdRef.current = null;
        }
    }, [settings['live_agent_config_id'][0], isTelegramIntegration]);

    // Fetch telegram groups when config changes (for Telegram)
    useEffect(() => {
        if (!settings['live_agent'][0]) {
            return;
        }

        const configId = settings['live_agent_config_id'][0];
        const prevConfigId = previousTelegramConfigIdRef.current;
        const configIdChanged = prevConfigId !== configId;


        // If we're switching integrations and config is not empty yet, it's stale - wait for it to clear
        if (isIntegrationSwitchingRef.current && configId && prevConfigId === null) {
            // Stale config from previous integration, skip
            return;
        }

        // Config was cleared during switch - update ref and mark transition complete
        if (!configId && isIntegrationSwitchingRef.current) {
            previousTelegramConfigIdRef.current = '';
            return;
        }

        if (configId && configIdChanged && isTelegramIntegration && isConfigFetched) {
            // Clear the switching flag - we have a valid new config now
            isIntegrationSwitchingRef.current = false;
            fetchTelegramUsers();
            previousTelegramConfigIdRef.current = configId;
        } else if (!configId) {
            // Clear users if no config is selected
            setTelegramUsers([]);
            setIsTelegramUsersFetched(true);
            previousTelegramConfigIdRef.current = '';
            return;
        } else if (!isTelegramIntegration) {
            setTelegramUsers([]);
            setIsTelegramUsersFetched(false);
        }
    }, [settings['live_agent'][0], settings['live_agent_config_id'][0], isTelegramIntegration, isConfigFetched]);

    /**
     * Handle config selection from Config component
     *
     * @param {object|null} config Config object
     */
    const handleConfigSelected = (config) => {
        if (config?.id) {
            // Determine integration from config's related_to
            const integration = getProviderFromConfigRelation(config.related_to);
            if (integration && integration !== selectedIntegration) {
                setSelectedIntegration(integration);
            }
        }
        // Only reset agents selection when config changes after initial load
        if (initialConfigLoadedRef.current) {
            settings['agent_ids'][1]([]);
        } else {
            initialConfigLoadedRef.current = true;
        }
    };

    /**
     * Fetch live agents (WP users linked to Slack/Telegram)
     *
     * @param {number} configId Config ID
     * @return {Promise<void>}
     */
    const fetchAgents = async (configId) => {
        if (!configId) {
            setAgents([]);
            setIsAgentsFetched(true);
            return;
        }

        setLoadingAgents(true);
        setLoading(prev => prev + 1);

        try {
            const response = await GetLiveAgents(configId);
            setAgents(response?.items?.length ? response.items : []);
        } catch (e) {
            setAgents([]);
            handleError(e, notifications.set, {
                title: __("Failed to fetch agents.", 'limb-chatbot'),
                description: e.message || __("Please check your connection and try again.", 'limb-chatbot'),
            });
        }

        setLoading(prev => prev - 1);
        setLoadingAgents(false);
        setIsAgentsFetched(true);
    };

    /**
     * Fetch Telegram users
     *
     * @return {Promise<void>}
     */
    const fetchTelegramUsers = async () => {
        const configId = settings['live_agent_config_id'][0];
        if (!configId) {
            setTelegramUsers([]);
            setIsTelegramUsersFetched(true);
            return;
        }

        setLoadingTelegramUsers(true);
        setLoading(prev => prev + 1);

        setLoading(prev => prev - 1);
        setLoadingTelegramUsers(false);
        setIsTelegramUsersFetched(true);
    };

    /**
     * Refresh Telegram users from API (called when popup opens)
     *
     * @return {Promise<void>}
     */
    const refreshTelegramUsers = async () => {
        const configId = settings['live_agent_config_id'][0];
        if (!configId || isRefreshingTelegramUsersRef.current) {
            return;
        }

        isRefreshingTelegramUsersRef.current = true;

        try {
            const response = await RefreshTelegramUsers(configId);
            if (response?.items) {
                setTelegramUsers(response.items);
            }
        } catch (e) {
            handleError(e);
        }

        isRefreshingTelegramUsersRef.current = false;
    };

    /**
     * Fetch Slack agents for the add popup
     *
     * @return {Promise<void>}
     */
    const fetchSlackAgents = async () => {
        const configId = settings['live_agent_config_id'][0];
        if (!configId) {
            return;
        }

        setLoadingSlackAgents(true);

        try {
            const response = await GetSlackAgents(configId);
            if (response?.items) {
                setSlackAgents(response.items);
            } else {
                setSlackAgents([]);
            }
        } catch (e) {
            setSlackAgents([]);
            handleError(e, notifications.set, {
                title: __("Failed to fetch Slack users.", 'limb-chatbot'),
                description: e.message || __("Please check your connection and try again.", 'limb-chatbot'),
            });
        }

        setLoadingSlackAgents(false);
    };

    /**
     * Fetch Telegram agents for the add popup
     *
     * @return {Promise<void>}
     */
    const fetchTelegramAgents = async () => {
        const configId = settings['live_agent_config_id'][0];
        if (!configId) {
            return;
        }

        setLoadingTelegramAgents(true);

        try {
            const response = await GetTelegramAgents(configId);
            if (response?.items) {
                setTelegramAgents(response.items);
            } else {
                setTelegramAgents([]);
            }
        } catch (e) {
            setTelegramAgents([]);
            handleError(e, notifications.set, {
                title: __("Failed to fetch Telegram users.", 'limb-chatbot'),
                description: e.message || __("Please check your connection and try again.", 'limb-chatbot'),
            });
        }

        setLoadingTelegramAgents(false);
    };

    /**
     * Set live agent IDs with sync between unified and legacy settings.
     * Updates both live_agent_ids (unified) and integration-specific legacy setting.
     * Open add agents popup
     */
    const openAddAgentsPopup = () => {
        setSelectedSlackAgents([]);
        setShowAddAgentsPopup(true);
        fetchSlackAgents();
    };

    /**
     * Open add Telegram agents popup
     */
    const openAddTelegramAgentsPopup = () => {
        setSelectedTelegramAgents([]);
        setShowAddTelegramAgentsPopup(true);
        fetchTelegramAgents();
    };

    /**
     * Create agents from selected Slack users
     *
     * @return {Promise<void>}
     */
    const handleCreateAgents = async () => {
        if (!selectedSlackAgents.length) {
            return;
        }

        const configId = settings['live_agent_config_id'][0];
        if (!configId) {
            return;
        }

        setCreatingAgents(true);
        setLoading(prev => prev + 1);

        try {
            const response = await CreateSlackAgents(configId, {ids: selectedSlackAgents});
            if (response?.items) {
                // Add new agents to the list
                setAgents(prev => [...prev, ...response.items]);
                // Auto-select the new agents
                const newAgentIds = response.items.map(item => item.id);
                settings['agent_ids'][1](prev => [...prev, ...newAgentIds]);
                // Close popup
                setShowAddAgentsPopup(false);
                setSelectedSlackAgents([]);
                handleSuccess(notifications.set, {
                    title: __("Agents added successfully.", 'limb-chatbot'),
                });
            }
        } catch (e) {
            handleError(e, notifications.set, {
                title: __("Failed to add agents.", 'limb-chatbot'),
                description: e.message || __("Please check your connection and try again.", 'limb-chatbot'),
            });
        }

        setLoading(prev => prev - 1);
        setCreatingAgents(false);
    };

    /**
     * Create agents from selected Telegram users
     *
     * @return {Promise<void>}
     */
    const handleCreateTelegramAgents = async () => {
        if (!selectedTelegramAgents.length) {
            return;
        }

        const configId = settings['live_agent_config_id'][0];
        if (!configId) {
            return;
        }

        setCreatingTelegramAgents(true);
        setLoading(prev => prev + 1);

        try {
            const response = await CreateTelegramAgents(configId, {ids: selectedTelegramAgents});
            if (response?.items) {
                // Add new agents to the list
                setAgents(prev => [...prev, ...response.items]);
                // Auto-select the new agents
                const newAgentIds = response.items.map(item => item.id);
                settings['agent_ids'][1](prev => [...prev, ...newAgentIds]);
                // Close popup
                setShowAddTelegramAgentsPopup(false);
                setSelectedTelegramAgents([]);
                handleSuccess(notifications.set, {
                    title: __("Telegram agents added successfully.", 'limb-chatbot'),
                });
            }
        } catch (e) {
            handleError(e, notifications.set, {
                title: __("Failed to add Telegram agents.", 'limb-chatbot'),
                description: e.message || __("Please check your connection and try again.", 'limb-chatbot'),
            });
        }

        setLoading(prev => prev - 1);
        setCreatingTelegramAgents(false);
    };

    /**
     * New config added callback
     *
     * @param {object} newConfig New config
     */
    const newConfigAdded = (newConfig) => {
        if (newConfig?.id) {
            // Use Config component's newConfigAdded method
            configRef.current?.newConfigAdded(newConfig);
        }
        setShowAddNewConfigPopup(false);
    };

    // Prepare agent options (from live agents / WP users)
    // Ensure value is a number to match the type saved in settings
    const agentOptions = agents.map(item => ({
        label: item.agent?.name || item.id,
        value: parseInt(item.id, 10),
        image: item.agent?.avatar_urls?.['24'] || null
    }));

    // Get existing agent emails for disabling in popup
    const existingAgentEmails = agents.map(item => item.agent?.email?.toLowerCase()).filter(Boolean);

    // Prepare Slack agent options for the add popup
    const slackAgentOptions = slackAgents.map(agent => ({
        label: agent.profile?.display_name_normalized || agent.profile?.real_name || agent.name || agent.id,
        value: agent.id,
        image: agent.profile?.image_24 || null,
        disabled: agent.profile?.email && existingAgentEmails.includes(agent.profile.email.toLowerCase())
    }));

    // Get existing Telegram agent IDs for disabling in popup
    const existingTelegramAgentIds = agents
        .filter(item => item.agent?.meta?.telegram_user_id)
        .map(item => String(item.agent.meta.telegram_user_id));

    // Prepare Telegram agent options for the add popup
    const telegramAgentOptions = telegramAgents.map(user => ({
        label: user.first_name ? `${user.first_name} ${user.last_name || ''}`.trim() : (user.username || user.id),
        value: String(user.chat_id || user.id),
        image: user.profile_photo_url || null,
        disabled: existingTelegramAgentIds.includes(String(user.id))
    }));

    // Prepare Telegram user options
    const telegramUserOptions = telegramUsers.map(user => ({
        label: user.first_name ? `${user.first_name} ${user.last_name || ''}`.trim() : (user.username || user.id),
        value: String(user.chat_id || user.id),
    }));

    return <>
        <TabSettings
            name={TAB_NAME}
            settings={settings}
            keysPrefix={SETTINGS_KEYS_PREFIX}
            validateField={validateField}
            tabLoading={loading}
            contentLoading={!showContent}
            shouldUpdatePreviewData
            dataFetched={value => setIsDataFetched(value)}
            notifications={notifications}
            initialDataRef={initialDataRef}
        >
            <Container className="lbaic-settings-cb-la">
                <div className="lbaic-settings-column">
                    <div className="lbaic-settings-column-in">
                        <Toggle
                            label={__("Live agent", 'limb-chatbot')}
                            isActive={settings['live_agent'][0]}
                            onClick={() => settings['live_agent'][1](!settings['live_agent'][0])}
                        />
                        <Description>
                            {__("Enable live agent support to allow human agents to take over conversations.", 'limb-chatbot')}
                        </Description>
                    </div>
                    <div className="lbaic-settings-column-in">
                        {settings['live_agent'][0] && (
                            <>
                                <Dropdown
                                    value={selectedIntegration}
                                    setValue={setSelectedIntegration}
                                    options={INTEGRATIONS}
                                    placeholder={__("Integration", 'limb-chatbot')}
                                />
                                <Description>
                                    {__("Select the integration platform for live agent support.", 'limb-chatbot')}
                                </Description>
                            </>
                        )}
                    </div>
                </div>
                {settings['live_agent'][0] && (
                    <>
                        {selectedIntegration && (
                            <div className="lbaic-settings-column">
                                <div className="lbaic-settings-column-in">
                                    <Config
                                        ref={configRef}
                                        aiProviderId={selectedIntegration}
                                        isDataFetched={isDataFetched}
                                        configId={settings['live_agent_config_id'][0]}
                                        setConfigId={settings['live_agent_config_id'][1]}
                                        configSelected={handleConfigSelected}
                                        setFetched={setIsConfigFetched}
                                        setLoading={setLoading}
                                        notifications={notifications}
                                        fieldProps={{
                                            addNew: () => setShowAddNewConfigPopup(true),
                                            errorMessage: errors['live_agent_config_id'][0],
                                            validate: value => validateField('live_agent_config_id', value),
                                        }}
                                    />
                                    <Description>
                                        {__("Select the API key to use for live agent support.", 'limb-chatbot')}
                                    </Description>
                                </div>
                                <div className="lbaic-settings-column-in">
                                    {isConfigSelected && isSlackIntegration && (
                                        <>
                                            <MultiSelect
                                                value={settings['agent_ids'][0]}
                                                setValue={settings['agent_ids'][1]}
                                                options={agentOptions}
                                                optionImageClassName="avatar"
                                                tagVarImageClassName="avatar"
                                                placeholder={__("Agents", 'limb-chatbot')}
                                                disabled={!isConfigSelected || loadingAgents || !isAgentsFetched}
                                                onAddNew={openAddAgentsPopup}
                                                errorMessage={errors['agent_ids'][0]}
                                                validate={value => validateField('agent_ids', value)}
                                            />
                                            <Description>
                                                {__("Select the agents who can respond to live agent requests.", 'limb-chatbot')}
                                            </Description>
                                        </>
                                    )}
                                    {isConfigSelected && isTelegramIntegration && (
                                        <>
                                            <MultiSelect
                                                value={settings['agent_ids'][0]}
                                                setValue={settings['agent_ids'][1]}
                                                options={agentOptions}
                                                optionImageClassName="avatar"
                                                tagVarImageClassName="avatar"
                                                placeholder={__("Agents", 'limb-chatbot')}
                                                disabled={!isConfigSelected || loadingAgents || !isAgentsFetched}
                                                onAddNew={openAddTelegramAgentsPopup}
                                                errorMessage={errors['agent_ids'][0]}
                                                validate={value => validateField('agent_ids', value)}
                                            />
                                            <Description>
                                                {__("Select the Telegram agents who can respond to live agent requests.", 'limb-chatbot')}
                                            </Description>
                                        </>
                                    )}
                                </div>
                            </div>
                        )}
                        {isConfigSelected && isSlackIntegration && (
                            <>
                                <div className="lbaic-settings-column">
                                    <div className="lbaic-settings-column-in">
                                        <Dropdown
                                            value={settings['agent_fetch_method'][0]}
                                            setValue={settings['agent_fetch_method'][1]}
                                            options={FETCH_METHODS}
                                            placeholder={__("Messages fetch method", 'limb-chatbot')}
                                            errorMessage={errors['agent_fetch_method'][0]}
                                            validate={value => validateField('agent_fetch_method', value)}>
                                            <Tooltip
                                                label={sprintf(__("%sPolling%s - Uses periodic requests to check for new messages. Simple but may show messages with a short delay.%s%sEvent Subscriptions%s - Messages sync instantly in the background for a faster chat experience. Requires a production site.", 'limb-chatbot'), '<strong>', '</strong>', '<br/>', '<strong>', '</strong>')}
                                                position="top"
                                                width={220}
                                            />
                                        </Dropdown>
                                        <Description>
                                            {__("Select how the chatbot should fetch messages.", 'limb-chatbot')}
                                        </Description>
                                    </div>
                                    <div className="lbaic-settings-column-in"/>
                                </div>
                                {settings['agent_fetch_method'][0] === 'event_subscription' && (
                                    <Notice
                                        type="warning"
                                        desc={sprintf(__("Please make sure you've added the %s endpoint in the %sEvent Subscriptions → Request URL%s and added the %s and %s events in the %sSubscribe to bot events%s.", 'limb-chatbot'), `<code>${LimbChatbot.rest.url}integrations/slack/events</code>`, '<strong>', '</strong>', `<code>message.channels</code>`, `<code>message.groups</code>`, '<strong>', '</strong>')}
                                        dismissible={false}
                                    />
                                )}
                            </>
                        )}
                        {isConfigSelected && isTelegramIntegration && (
                            <>
                                <div className="lbaic-settings-column">
                                    <div className="lbaic-settings-column-in">
                                        <Dropdown
                                            value={settings['agent_fetch_method'][0]}
                                            setValue={settings['agent_fetch_method'][1]}
                                            options={FETCH_METHODS}
                                            placeholder={__("Messages fetch method", 'limb-chatbot')}
                                            errorMessage={errors['agent_fetch_method'][0]}
                                            validate={value => validateField('agent_fetch_method', value)}>
                                            <Tooltip
                                                label={sprintf(__("%sPolling%s - Uses periodic requests to check for new messages. Simple but may show messages with a short delay.%s%sEvent Subscription%s - Messages sync instantly via webhook. Requires a production site with HTTPS.", 'limb-chatbot'), '<strong>', '</strong>', '<br/>', '<strong>', '</strong>')}
                                                position="top"
                                                width={220}
                                            />
                                        </Dropdown>
                                        <Description>
                                            {__("Select how the chatbot should fetch messages.", 'limb-chatbot')}
                                        </Description>
                                    </div>
                                    <div className="lbaic-settings-column-in"/>
                                </div>
                            </>
                        )}
                    </>
                )}
            </Container>
        </TabSettings>
        {showAddNewConfigPopup && selectedIntegration && (
            <AddEditConfig
                aiProviderId={selectedIntegration}
                added={newConfigAdded}
                close={() => setShowAddNewConfigPopup(false)}
                notifications={notifications}
            />
        )}
        {showAddAgentsPopup && (
            <PopupContainer
                title={__("Add agents", 'limb-chatbot')}
                close={() => setShowAddAgentsPopup(false)}
                loading={loadingSlackAgents || creatingAgents}
                footer={(
                    <>
                        <Button
                            type="secondary"
                            label={__("Cancel", 'limb-chatbot')}
                            onClick={() => setShowAddAgentsPopup(false)}
                            disabled={creatingAgents}
                        />
                        <Button
                            type="primary"
                            label={__("Add", 'limb-chatbot')}
                            onClick={handleCreateAgents}
                            disabled={!selectedSlackAgents.length || creatingAgents}
                            loading={creatingAgents}
                        />
                    </>
                )}
            >
                <div className="lbaic-settings-column">
                    <div className="lbaic-settings-column-in">
                        <MultiSelect
                            value={selectedSlackAgents}
                            setValue={setSelectedSlackAgents}
                            options={slackAgentOptions}
                            optionImageClassName="avatar"
                            tagVarImageClassName="avatar"
                            placeholder={__("Slack agents", 'limb-chatbot')}
                            disabled={loadingSlackAgents}
                        />
                        <Description>{__("Select Slack users to import as Live Agents.", 'limb-chatbot')} <a href="https://wpaichatbot.com/documentation/connecting-to-human-support/setting-up-live-agent/#step-4-select-live-agents" target="_blank">{__("Learn more", 'limb-chatbot')}</a></Description>
                    </div>
                </div>
            </PopupContainer>
        )}
        {showAddTelegramAgentsPopup && (
            <PopupContainer
                title={__("Add Telegram agents", 'limb-chatbot')}
                close={() => setShowAddTelegramAgentsPopup(false)}
                loading={loadingTelegramAgents || creatingTelegramAgents}
                footer={(
                    <>
                        <Button
                            type="secondary"
                            label={__("Cancel", 'limb-chatbot')}
                            onClick={() => setShowAddTelegramAgentsPopup(false)}
                            disabled={creatingTelegramAgents}
                        />
                        <Button
                            type="primary"
                            label={__("Add", 'limb-chatbot')}
                            onClick={handleCreateTelegramAgents}
                            disabled={!selectedTelegramAgents.length || creatingTelegramAgents}
                            loading={creatingTelegramAgents}
                        />
                    </>
                )}
            >
                <div className="lbaic-settings-column">
                    <div className="lbaic-settings-column-in">
                        <MultiSelect
                            value={selectedTelegramAgents}
                            setValue={setSelectedTelegramAgents}
                            options={telegramAgentOptions}
                            optionImageClassName="avatar"
                            tagVarImageClassName="avatar"
                            placeholder={__("Telegram agents", 'limb-chatbot')}
                            disabled={loadingTelegramAgents}
                            refreshOptions={fetchTelegramAgents}
                        />
                        <Description>{__("Select Telegram users to add as Live Agents. If a user doesn't appear in the list, ask them to send a message to your bot first, then click Refresh.", 'limb-chatbot')}</Description>
                    </div>
                </div>
            </PopupContainer>
        )}
    </>;
}