import {useEffect, useState, useRef} from "@wordpress/element";
import {__} from "@wordpress/i18n";
import Dropdown from "../../../../../../../../../../fields/dropdown";
import Description from "../../../../../../../../../../sections/description";
import {GetSlackChannels} from "../../../../../../../../../../../rest/integrations";
import {handleError} from "../../../../../../../../../../../helpers/notifications";
import {getRequiredValidator} from "../../../../_utils/validations";

export default function SlackChannel({callback, updateField, notifications}) {
    const [channelError, setChannelError] = useState(false);
    const [channels, setChannels] = useState([]);
    const [isChannelsLoading, setIsChannelsLoading] = useState(false);
    const [isChannelsFetched, setIsChannelsFetched] = useState(false);
    const previousConfigIdRef = useRef(null);

    /**
     * Fetch Slack channels
     */
    const fetchChannels = async (configId) => {
        if (!configId) {
            setChannels([]);
            setIsChannelsFetched(false);
            return;
        }

        setIsChannelsLoading(true);
        try {
            const response = await GetSlackChannels(configId);
            // Handle response with items property (API returns {items: {...}, total: number})
            if (response?.items) {
                // Convert channels object to array
                const channelsArray = Object.values(response.items);
                setChannels(channelsArray);
                setIsChannelsFetched(true);
            } else if (response?.success && response.channels) {
                // Fallback for legacy response format
                const channelsArray = Object.values(response.channels);
                setChannels(channelsArray);
                setIsChannelsFetched(true);
            } else {
                setChannels([]);
                setIsChannelsFetched(true);
                if (response && response.success === false) {
                    handleError({message: response.message || __("Failed to fetch channels.", 'limb-chatbot')}, notifications.set, {
                        title: __("Failed to fetch Slack channels.", 'limb-chatbot'),
                        description: response.message || __("Please check your connection and try again.", 'limb-chatbot'),
                    });
                }
            }
        } catch (e) {
            setChannels([]);
            setIsChannelsFetched(true);
            handleError(e, notifications.set, {
                title: __("Failed to fetch Slack channels.", 'limb-chatbot'),
                description: e.message || __("Please check your connection and try again.", 'limb-chatbot'),
            });
        } finally {
            setIsChannelsLoading(false);
        }
    };

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

    // Fetch channels when config_id changes
    useEffect(() => {
        const configId = callback?.config?.config_id;
        const configIdChanged = previousConfigIdRef.current !== configId;

        if (configId) {
            // Always refetch if config_id changed
            if (configIdChanged) {
                setChannels([]);
                setIsChannelsFetched(false);
                fetchChannels(configId);
                previousConfigIdRef.current = configId;
            }
        } else {
            // Clear channels if no config is selected
            setChannels([]);
            setIsChannelsFetched(false);
            previousConfigIdRef.current = null;
        }
    }, [callback?.config?.config_id]);

    return (
        <div className="lbaic-settings-column">
            <div className="lbaic-settings-column-in">
                <Dropdown
                    value={callback?.config?.channel || null}
                    setValue={(channel) => {
                        if (channel && typeof channel === 'object' && channel.id) {
                            updateChannel(channel.id);
                        } else if (typeof channel === 'string') {
                            updateChannel(channel);
                        } else {
                            updateChannel(null);
                        }
                    }}
                    options={channels.map(channel => ({
                        label: channel.is_private ? '🔒' : '#' + ' ' + channel.name,
                        value: channel.id,
                        id: channel.id,
                    }))}
                    placeholder={__("Channel", 'limb-chatbot')}
                    validate={getRequiredValidator(setChannelError)}
                    errorMessage={channelError}
                    disabled={!callback?.config?.config_id || isChannelsLoading || !isChannelsFetched}
                />
                <Description>
                    {__("Select a Slack channel to send the notification to.", 'limb-chatbot')}
                </Description>
            </div>
        </div>
    );
}

