import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
import { useContext, useEffect, useRef, useState } from 'react';
import { nlpDropdownDefaultCSSData, } from './NlpDropDownType';
import useClickOutside from '../../../../hooks/useClickOutside';
import { checkEmpty } from '../../../../utils/checkEmpty/checkEmpty';
import './NlpDropdown.scss';
import Typography from '../../../Typography';
import { ThemeContext } from '../../../ThemeProvider/ThemeProvider';
import classNames from 'classnames';
import Icon from '../../../Icon';
import IconButton from '../../../IconButton';
import { useIntersectionObserver } from '../../../../hooks/useIntersectionObserver';
import Tooltip from '../../../Tooltip';
const NlpDropdown = ({ onSelectBlur, onSelectOptionSelector, dropdownPosition, options = [], optionZIndex = 100, inputRef, webServiceClick = () => { }, containerWidth, loadMoreOptions, chipRef, isWebservice = true, dropDownMessage = '', }) => {
    const [nlpData, setNlpData] = useState(null);
    const [showNlpDetails, setShowNlpDetails] = useState('');
    const themeContext = useContext(ThemeContext);
    const currentTheme = themeContext?.currentTheme;
    const optionsWrapperRef = useRef(null);
    const [focusedIndex, setFocusedIndex] = useState(-1);
    useClickOutside(optionsWrapperRef, onSelectBlur, [inputRef, chipRef]);
    const { positionX, positionY, width, fromBottom } = dropdownPosition;
    const { margin, optionHeight, selectInputHeight, dropDownWrapperPadding } = nlpDropdownDefaultCSSData;
    const updateDropdownPosition = () => {
        let dropdownContainerHeight;
        if (checkEmpty(options)) {
            dropdownContainerHeight = 5 * optionHeight + 2 * dropDownWrapperPadding;
        }
        else if (options.length > 0) {
            dropdownContainerHeight = 5 * optionHeight + 2 * dropDownWrapperPadding;
        }
        else {
            dropdownContainerHeight =
                options.length * optionHeight + 2 * dropDownWrapperPadding;
        }
        if (fromBottom > dropdownContainerHeight + margin + 80) {
            return {
                left: positionX,
                top: positionY,
                width: width,
                zIndex: optionZIndex,
            };
        }
        return {
            zIndex: optionZIndex,
            left: positionX,
            width: width,
            top: positionY - selectInputHeight - 92 - dropdownContainerHeight - margin,
        };
    };
    const getNLPType = (nlpType) => {
        let label = '';
        let className = '';
        if (nlpType === 'NLP') {
            label = 'NLP';
            className = 'ff-nlp';
        }
        else if (nlpType === 'STEP_GROUP') {
            label = 'SG';
            className = 'ff-sg';
        }
        else if (nlpType === 'PROGRAM_ELEMENTS') {
            label = 'PE';
            className = 'ff-pe';
        }
        else if (nlpType === 'WORKBENCH_REQUEST') {
            label = 'WS';
            className = 'ff-ws';
        }
        else {
            label = '--';
            className = 'nlp-default';
        }
        return { label, className };
    };
    const getPlatformIcon = ({ platform, nlpType }) => {
        if (nlpType === 'NLP') {
            if (platform === 'Web') {
                return _jsx(Icon, { name: "web_icon", height: 10, width: 10 });
            }
            else if (platform === 'Android') {
                return _jsx(Icon, { name: "android_icon", height: 10, width: 10 });
            }
            else if (platform === 'iOS') {
                return (_jsx(Icon, { name: "ios_icon", height: 10, width: 10, color: "var(--dotted-border-color)" }));
            }
            else if (platform === 'Generic') {
                return _jsx(Icon, { name: "mobile_icon", height: 10, width: 10 });
            }
            else {
                return _jsx(Icon, { name: "common_nlp", height: 10, width: 10 });
            }
        }
        else if (nlpType === 'WORKBENCH_REQUEST') {
            if (platform === 'Webservice') {
                return _jsx(Icon, { name: "web_service_icon", height: 8, width: 8 });
            }
        }
        return _jsx(_Fragment, {});
    };
    useIntersectionObserver(['ff-nlp-dropdown-pagination'], {
        root: document.getElementById('ff-nlp-dropdown-options-wrapper'),
        rootMargin: '0px',
        threshold: 0.1,
        onIntersect: (entry, _observer) => {
            if (entry.isIntersecting) {
                if (loadMoreOptions) {
                    loadMoreOptions();
                }
            }
        },
    });
    useEffect(() => {
        if (focusedIndex >= 0 && focusedIndex < options.length) {
            const newOption = options[focusedIndex];
            setNlpData(newOption);
            setShowNlpDetails('show');
        }
        else if (focusedIndex >= options.length) {
            setNlpData(null);
            setShowNlpDetails('');
            setFocusedIndex(-1);
        }
        const handleKeyDown = (event) => {
            if (!options.length)
                return;
            switch (event.key) {
                case 'ArrowDown':
                    event.preventDefault();
                    setFocusedIndex((prev) => (prev < options.length - 1 ? prev + 1 : 0));
                    break;
                case 'ArrowUp':
                    event.preventDefault();
                    setFocusedIndex((prev) => (prev > 0 ? prev - 1 : options.length - 1));
                    break;
                case 'Enter':
                    if (focusedIndex >= 0) {
                        if (options[focusedIndex]) {
                            onSelectOptionSelector(options[focusedIndex]);
                        }
                    }
                    break;
                default:
                    break;
            }
        };
        document.addEventListener('keydown', handleKeyDown);
        return () => {
            document.removeEventListener('keydown', handleKeyDown);
        };
    }, [options, focusedIndex]);
    useEffect(() => {
        if (focusedIndex < 0)
            return;
        const el = document.getElementById(`ff-nlp-option-${focusedIndex}`);
        if (el) {
            el.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
        }
    }, [focusedIndex]);
    useEffect(() => {
        if (!options?.length)
            return;
        const dropdown = optionsWrapperRef.current;
        if (!dropdown)
            return;
        const stopScroll = (e) => {
            if (dropdown.contains(e.target))
                return;
            e.stopPropagation();
            e.preventDefault();
        };
        document.body.addEventListener('wheel', stopScroll, { passive: false });
        document.body.addEventListener('touchmove', stopScroll, { passive: false });
        return () => {
            document.body.removeEventListener('wheel', stopScroll);
            document.body.removeEventListener('touchmove', stopScroll);
        };
    }, [options]);
    const getDisplayName = (item) => {
        return (item?.searchName ||
            item?.displayName ||
            item?.desc ||
            item?.name ||
            item?.nlpName ||
            '---');
    };
    return (_jsx("div", { className: "ff-nlp-dropdown-wrapper", children: _jsxs("div", { ref: optionsWrapperRef, style: { ...updateDropdownPosition(), width: containerWidth }, className: classNames('ff-nlp-options-wrapper', currentTheme), onMouseLeave: () => setShowNlpDetails('hide'), children: [_jsxs("div", { className: "ff-nlp-options-wrapper-main", children: [_jsx("div", { className: "ff-nlp-options-primary-wrapper", id: "ff-nlp-dropdown-options-wrapper", children: !checkEmpty(options) ? (_jsxs(_Fragment, { children: [options.map((option, index) => (_jsx("div", { onMouseEnter: () => {
                                            setNlpData(option);
                                            setShowNlpDetails('show');
                                        }, id: `ff-nlp-option-${index}`, children: _jsx("div", { onMouseEnter: () => setFocusedIndex(index), onClick: () => onSelectOptionSelector(option), onKeyDown: (event) => {
                                                if (event.key === 'Enter') {
                                                    onSelectOptionSelector(option);
                                                }
                                            }, children: _jsxs(Typography, { as: "div", lineHeight: "30px", fontSize: 12, className: classNames('ff-nlp-option', currentTheme, {
                                                    'ff-nlp-option--selected': focusedIndex === index,
                                                }), children: [_jsx(Tooltip, { title: option.platform, children: _jsx("span", { children: _jsx(Typography, { className: `nlp-categories ${getNLPType(option.nlpType).className}`, fontWeight: "regular", fontSize: 8, lineHeight: "32px", children: getNLPType(option.nlpType).label }) }) }), _jsx("span", { children: getPlatformIcon(option) }), getDisplayName(option)] }) }) }, `ff-nlp-option-${index}`))), _jsx("div", { id: "ff-nlp-dropdown-pagination" })] })) : (_jsx(Typography, { textAlign: "center", lineHeight: "32px", as: "p", color: "var(--ff-nlp-text-color)", className: "ff-nlp-no-option", children: checkEmpty(dropDownMessage)
                                    ? 'No Results Found'
                                    : dropDownMessage })) }), isWebservice && (_jsx("div", { children: _jsx("div", { className: showNlpDetails === 'show'
                                    ? 'ff-nlp-web-service-div'
                                    : 'ff-nlp-primary-web-service-div', children: _jsx(IconButton, { iconName: "plus_user_icon", label: "Web Service", onClick: () => {
                                        onSelectBlur();
                                        webServiceClick();
                                    } }) }) }))] }), _jsx("div", { className: showNlpDetails === 'show' ? 'ff-nlp-data-show' : 'ff-nlp-data-hide', children: _jsxs("div", { className: "ff-nlp-data-side-menu", children: [nlpData?.videoSrc && (_jsxs(Typography, { className: "nlp-details-header", fontWeight: "semi-bold", fontSize: 10, children: ["Video", _jsx("div", { className: "nlp-details ", children: _jsx("video", { src: nlpData.videoSrc, controls: true, className: "nlp-video-player", width: "100%", children: "Your browser does not support the video tag." }) })] })), _jsxs(Typography, { className: "nlp-details-header", fontWeight: "semi-bold", fontSize: 12, children: ["NLP Details", _jsx(Typography, { className: "nlp-details", fontWeight: "regular", fontSize: 12, children: getDisplayName(nlpData) })] }), _jsxs(Typography, { className: "nlp-details-header", fontWeight: "semi-bold", fontSize: 12, children: ["Description", _jsx(Typography, { className: "nlp-details", fontWeight: "regular", fontSize: 12, children: nlpData?.description || '--' })] }), nlpData?.nlpType === 'STEP_GROUP' && (_jsx(_Fragment, { children: _jsxs(Typography, { className: "nlp-details-header", fontWeight: "semi-bold", fontSize: 12, children: ["Path", _jsx(Typography, { className: "nlp-details", fontWeight: "regular", fontSize: 12, children: nlpData?.path ? nlpData?.path : '---' })] }) })), _jsx(Typography, { className: "nlp-details-header", fontWeight: "semi-bold", fontSize: 12, children: "Inputs" }), nlpData?.stepInputs?.length ? (nlpData.stepInputs.map((stepInput, index) => {
                                const stepInputType = stepInput.type
                                    ? stepInput?.type?.split('.')?.pop()
                                    : '--';
                                return (_jsx("div", { children: _jsxs(Typography, { className: "nlp-details-header", fontWeight: "semi-bold", fontSize: 12, children: ["Input", index + 1, _jsxs(Typography, { className: "nlp-details", fontWeight: "regular", fontSize: 12, children: ["type: ", stepInputType] }), _jsxs(Typography, { className: "nlp-details", fontWeight: "regular", fontSize: 12, children: ["name: ", stepInput.name || '--'] })] }) }, index));
                            })) : (_jsx("div", { className: "nlp-details", children: "--" })), _jsxs(Typography, { className: "nlp-details-header", fontWeight: "semi-bold", fontSize: 12, children: ["Output", _jsx(Typography, { className: "nlp-details ", fontWeight: "regular", fontSize: 12, children: nlpData?.returnType || '--' })] })] }) })] }) }));
};
export default NlpDropdown;
//# sourceMappingURL=NlpDropdown.js.map