import { SessionManager } from '@stack-spot/auth-react';
import { debounce } from 'lodash';
import { useCallback, useEffect, useRef, useState } from 'react';
import { useWatchJinjaExpression } from '../../form/hooks.js';
import { isJinjaExpression } from '../../utils/jinja.js';
import { isUrlValid } from '../../utils/url.js';
const minTimeBetweenRequestsMS = 1000;
export function useSelectOptions(variable) {
    const [options, setOptions] = useState(variable.config.metadata?.items?.length ? variable.config.metadata?.items : variable.config.metadata?.itemsValues);
    const [isLoading, setLoading] = useState(isJinjaExpression(variable.config.metadata?.externalItems));
    const externalOptions = useWatchJinjaExpression(variable.config.metadata?.externalItems);
    const abortController = useRef();
    const fetchOptions = useCallback(debounce(async (url) => {
        let error = '';
        if (isUrlValid(url)) {
            abortController.current?.abort();
            abortController.current = new AbortController();
            setLoading(true);
            try {
                const response = await (url.match(/\.stackspot\.com$/)
                    ? SessionManager.instance?.getSession().fetch(url, { signal: abortController.current.signal })
                    : fetch(url, { signal: abortController.current.signal }));
                if (response?.ok) {
                    try {
                        const result = await response.json();
                        if (Array.isArray(result))
                            setOptions(result.map(r => `${r}`));
                    }
                    catch (e) {
                        error = e.message || `${e}`;
                    }
                }
                else {
                    let responseMessage;
                    try {
                        responseMessage = await response?.text();
                    }
                    catch { /* do nothing */ }
                    error = `Status ${response?.status}. Response: ${responseMessage}`;
                }
            }
            catch (e) {
                error = e.message || `${e}`;
            }
            if (error) {
                setOptions([]);
                setLoading(false);
                // eslint-disable-next-line no-console
                console.error(`Error while retrieving options for select "${variable.path}" in the dynamic form. ${error}.`);
            }
            setLoading(false);
        }
        else {
            setOptions([]);
            setLoading(false);
        }
    }, minTimeBetweenRequestsMS), []);
    useEffect(() => {
        if (variable.config.metadata?.externalItems) {
            fetchOptions(`${externalOptions}`);
        }
    }, [externalOptions]);
    return [options ?? [], isLoading];
}
//# sourceMappingURL=use-select-options.js.map