import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useReducer, useRef, useEffect, useState, useLayoutEffect, } from 'react';
import { checkEmpty } from '../../utils/checkEmpty/checkEmpty';
import { createPortal } from 'react-dom';
import classNames from 'classnames';
import Dropdown from './components/NlpDropDown/NlpDropdown';
import Icon from '../Icon';
import './NLPInput.scss';
import usePortalPosition from '../../hooks/usePortalPosition';
import Typography from '../Typography';
import ChipsAccordion from './components/ChipsFolder/ChipsAccordion';
const nlpInputReducer = (state, action) => {
    switch (action.type) {
        case 'FOCUS_INPUT':
            return {
                ...state,
                isInputFocused: true,
                isIconClick: true,
                showOptions: true,
            };
        case 'BLUR_INPUT':
            return {
                ...state,
                isInputFocused: false,
                option: action.payload.option,
                isIconClick: false,
                showOptions: false,
                dropdownPosition: {
                    positionX: 0,
                    positionY: 0,
                    width: 0,
                    fromBottom: 0,
                },
            };
        case 'UPDATE_DROPDOWN_POSITION':
            const { positionX, positionY, width, fromBottom } = action.payload || {};
            return {
                ...state,
                dropdownPosition: {
                    positionX,
                    positionY,
                    width,
                    fromBottom,
                },
            };
        case 'UPDATE_OPTION':
            return {
                ...state,
                option: action.payload,
            };
        case 'SHOW_ERROR':
            return {
                ...state,
                isInputFocused: true,
                isIconClick: false,
                showOptions: false,
                option: action.payload.option,
                dropdownPosition: {
                    positionX: 0,
                    positionY: 0,
                    width: 0,
                    fromBottom: 0,
                },
            };
        default:
            return state;
    }
};
const NlpInput = ({ label = '', leftIcon, rightIcon, rightIconColor, showLabel = true, onHelpIconClick = () => { }, aiIconClick = () => { }, webServiceClick = () => { }, containerWidth = '', optionsList = [], selectedOption = {
    displayName: '',
    projectId: '',
    nlpType: '',
    platform: '',
}, onChange = () => { }, errorMsg = '', className = '', optionZIndex = 100, disabled = false, borderRadius = true, showBorder = true, required = false, value = '', onSelect = () => { }, chipOptionList, selectedChips, loadMoreOptions = () => { }, isWebservice = true, closeInputOnOutsideClick = () => { }, tooltipText = 'Help', ChipsAccordionWidth = '27.8%', dropDownMessage = '', }) => {
    const initialState = {
        isInputFocused: false,
        isIconClick: false,
        showOptions: false,
        option: checkEmpty(selectedOption) &&
            typeof selectedOption?.displayName === 'string'
            ? selectedOption.displayName
            : '',
        dropdownPosition: { positionX: 0, positionY: 0, width: 0, fromBottom: 0 },
    };
    const [selectControlState, dispatch] = useReducer(nlpInputReducer, initialState);
    const [inputVal, setInputVal] = useState(selectedOption);
    const [tooltipStyle, setTooltipStyle] = useState({});
    const helpIconClicked = useRef(false);
    useEffect(() => {
        const updatedDisplayName = typeof selectedOption.displayName === 'string'
            ? selectedOption.displayName
            : String(selectedOption.displayName ?? '');
        if (updatedDisplayName !== inputVal.displayName) {
            setInputVal({ ...selectedOption, displayName: updatedDisplayName });
        }
    }, [selectedOption]);
    useEffect(() => {
        if (value) {
            handleSelectAction('FOCUS_INPUT');
        }
    }, [value]);
    const DropDownRef = useRef(null);
    const InputRef = useRef(null);
    const ChipRef = useRef(null);
    const { isInputFocused, isIconClick, showOptions, dropdownPosition, option } = selectControlState;
    const calculatePosition = usePortalPosition(DropDownRef, showOptions);
    const handleSelectAction = (actionType) => {
        if (!disabled) {
            if (actionType === 'SHOW_ERROR' || actionType === 'BLUR_INPUT') {
                dispatch({
                    type: actionType,
                    payload: {
                        option: typeof selectedOption.displayName === 'string'
                            ? selectedOption.displayName
                            : String(selectedOption.displayName ?? ''),
                    },
                });
            }
            else {
                dispatch({ type: actionType });
            }
        }
    };
    const onSelectInputChange = (e) => {
        if (disabled)
            return;
        onChange(e);
    };
    const onSelectBlur = () => {
        if (disabled)
            return;
        if (helpIconClicked.current) {
            helpIconClicked.current = false;
            return;
        }
        if (errorMsg) {
            handleSelectAction('SHOW_ERROR');
        }
        else {
            handleSelectAction('BLUR_INPUT');
            closeInputOnOutsideClick();
        }
    };
    const onSelectOptionSelector = (option) => {
        onSelect(option);
    };
    const onSelectUpdatePosition = () => {
        if (!showOptions || !DropDownRef?.current || disabled)
            return;
        const { positionX, positionY, width, fromBottom } = calculatePosition(DropDownRef);
        dispatch({
            type: 'UPDATE_DROPDOWN_POSITION',
            payload: { positionX, positionY, width, fromBottom },
        });
    };
    const onSelectToggleScroll = (isEnabled) => {
        const bodyScrollWidth = window.innerWidth - document.body.clientWidth;
        document.body.style.paddingRight = isEnabled ? '' : `${bodyScrollWidth}px`;
        document.body.style.overflow = isEnabled ? '' : 'hidden';
    };
    useLayoutEffect(() => {
        if (disabled)
            return;
        if (showOptions) {
            onSelectToggleScroll(!showOptions);
        }
        onSelectUpdatePosition();
        const handleResizeOrScroll = () => onSelectUpdatePosition();
        window.addEventListener('resize', handleResizeOrScroll);
        window.addEventListener('scroll', handleResizeOrScroll);
        return () => {
            onSelectToggleScroll(true);
            window.removeEventListener('resize', handleResizeOrScroll);
            window.removeEventListener('scroll', handleResizeOrScroll);
        };
    }, [showOptions]);
    useEffect(() => {
        if (errorMsg) {
            handleSelectAction('SHOW_ERROR');
        }
    }, []);
    useEffect(() => {
        handleSelectAction('FOCUS_INPUT');
    }, []);
    const applyActiveOptionClasses = !isInputFocused && Boolean(option);
    useEffect(() => {
        const inputEl = InputRef.current;
        if (!inputEl)
            return;
        let scrollContainer = inputEl.parentElement;
        while (scrollContainer && scrollContainer !== document.body) {
            const style = getComputedStyle(scrollContainer);
            if (['scroll', 'auto'].includes(style.overflowY)) {
                break;
            }
            scrollContainer = scrollContainer.parentElement;
        }
        if (!scrollContainer)
            return;
        const originalOverflow = scrollContainer.style.overflow;
        const shouldFreeze = showOptions || chipOptionList;
        if (shouldFreeze) {
            scrollContainer.style.overflow = 'hidden';
        }
        else {
            scrollContainer.style.overflow = originalOverflow || 'auto';
        }
        return () => {
            scrollContainer.style.overflow = originalOverflow || 'auto';
        };
    }, [showOptions, chipOptionList]);
    return (_jsxs("section", { className: "main-section", children: [_jsxs("div", { className: classNames(`ff-nlp-input-wrapper ${className}`), children: [_jsxs("div", { className: "ff-nlp-input", children: [_jsx("input", { type: "text", className: classNames('ff-nlp-input-container', {
                                    'ff-nlp-input-container--default': !isInputFocused,
                                    'ff-nlp-input-container--active': applyActiveOptionClasses,
                                    'ff-nlp-input-container--no-label': !showLabel,
                                    'ff-nlp-input-container--error': errorMsg && !isInputFocused && !Boolean(option),
                                    'ff-nlp-input-container--border-radius': !borderRadius,
                                    'ff-nlp-input-container--disable': disabled,
                                    'ff-nlp-input-container--no-border': !showBorder,
                                }), style: {
                                    zIndex: optionZIndex,
                                    paddingLeft: '32px',
                                }, onFocus: () => handleSelectAction('FOCUS_INPUT'), onChange: onSelectInputChange, value: value, disabled: disabled, autoComplete: "off", spellCheck: "false", ref: InputRef, autoFocus: true }), _jsxs("div", { className: "ff-nlp-icon-container", children: [_jsx(Icon, { name: leftIcon || 'ai_search', className: "ff-nlp-help_icon", width: 16, height: 16, onClick: aiIconClick }), _jsx(Typography, { className: "icon-label", fontSize: 10, children: "Search With Ai" })] }), showLabel && (_jsxs("div", { className: classNames('ff-nlp-input-label', 'ff-nlp-input-label--default', {
                                    'ff-nlp-input-label--active': value || Boolean(option),
                                    'ff-nlp-input-label--error': errorMsg,
                                }), children: [required && (_jsx(Typography, { color: "var(--$error-light)", className: "ff-nlp-input-label--required", children: "*" })), label] })), _jsxs("div", { className: "help-icon-container", onMouseDown: () => (helpIconClicked.current = true), style: { zIndex: optionZIndex }, children: [_jsx("span", { className: classNames('ff-nlp-input-arrow', {
                                            'ff-nlp-input-arrow--down': !isIconClick,
                                            'ff-nlp-input-arrow--no-label': !showLabel,
                                        }), onMouseEnter: (e) => {
                                            const rect = e.target.getBoundingClientRect();
                                            setTooltipStyle({
                                                top: `${rect.top + window.scrollY - 20}px`,
                                                left: `${rect.left + window.scrollX + rect.width * 0.5}px`,
                                                visibility: 'visible',
                                                opacity: 1,
                                                transitionDelay: '0s',
                                            });
                                        }, onMouseLeave: () => setTooltipStyle((prev) => ({
                                            ...prev,
                                            visibility: 'hidden',
                                            opacity: 0,
                                        })), children: _jsx(Icon, { name: rightIcon || '', height: 16, width: 16, onClick: onHelpIconClick, color: rightIconColor }) }), createPortal(_jsx(Typography, { className: "help-icon-label", fontSize: 10, style: tooltipStyle, children: tooltipText }), document.body)] }), _jsx("fieldset", { className: classNames('ff-nlp-input-fieldset', {
                                    'ff-nlp-input-fieldset--no-label': !showLabel,
                                    'ff-nlp-input-fieldset--default': !isInputFocused,
                                    'ff-nlp-input-fieldset--active': isInputFocused,
                                    'ff-nlp-input-fieldset--option': applyActiveOptionClasses,
                                    'ff-nlp-input-fieldset--error': errorMsg,
                                    'ff-nlp-input-fieldset--border-radius': !borderRadius,
                                    'ff-nlp-input-fieldset--no-border': !showBorder,
                                }) })] }), errorMsg && (_jsx(Typography, { className: "ff-nlp-input-wrapper-error-text", fontSize: 8, color: 'var(--error-light)', children: errorMsg })), _jsx("div", { ref: DropDownRef, children: showOptions &&
                            createPortal(_jsx(Dropdown, { onSelectBlur: onSelectBlur, onSelectOptionSelector: onSelectOptionSelector, dropdownPosition: dropdownPosition, options: optionsList, optionZIndex: optionZIndex, inputRef: InputRef, webServiceClick: webServiceClick, containerWidth: containerWidth, loadMoreOptions: loadMoreOptions, chipRef: ChipRef, isWebservice: isWebservice, dropDownMessage: dropDownMessage }), document.body) })] }), _jsx("div", { className: "chips-accordion-content", children: chipOptionList && chipOptionList.length > 0 && (_jsx(ChipsAccordion, { chipOptionList: chipOptionList, selectedChips: selectedChips, optionZIndex: optionZIndex, ref: ChipRef, inputRef: InputRef, ChipsAccordionWidth: ChipsAccordionWidth })) })] }));
};
export default NlpInput;
//# sourceMappingURL=NlpInput.js.map