import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useState, useEffect, forwardRef, useImperativeHandle, useRef, } from 'react';
import { checkEmpty } from '../../utils/checkEmpty/checkEmpty';
import VariableDropdown from '../Editor/VariableDropdown';
import Icon from '../Icon';
import Input from '../Input';
import './VariableSuggestionInputDropDown.scss';
import OptionsDropdown from './OptionsDropdown';
import Tooltip from '../Tooltip';
import Typography from '../Typography';
import classNames from 'classnames';
const VariableSuggestionInputDropDown = forwardRef(({ label = '', hashInputValue = '', setHashInputValue, variableList = [], placeholder = 'Enter text', onChange, onPaste, onCreateVariableClick, handleClearInput, value = '', dropdownWidth = '100%', dropdownHeight = '160px', isHash = false, isOnlyHash = false, dataFiles = [], showAddVariableIcon = true, helperText = '', error, autoComplete = 'off', required = false, zIndex = 9999, truncateTextValue = 34, formProps = {}, getSelectedVariable = () => { }, symbol = '$', type = 'text', clearIcon = true, inputTitle = '', onBlur, helperTextWidth, iconProps = {
    isShowIcon: false,
    iconName: '',
    iconToolTipTitle: '',
    isIconDisable: false,
    iconColor: '',
    onIconClick: () => { },
}, ...props }, ref) => {
    const [showDropdown, setShowDropdown] = useState(false);
    const [isDropdownClicked, setIsDropdownClicked] = useState(false);
    const [highlightedIndex, setHighlightedIndex] = useState(0);
    const [isFocused, setIsFocused] = useState(false);
    const [cursorPosition, setCursorPosition] = useState(null);
    const [findCursor, setFindCursor] = useState(0);
    const [showCreateVariableIcon, setShowCreateVariableIcon] = useState(false);
    const [filteredOptions, setFilteredOptions] = useState([]);
    const inputRef = useRef(null);
    const containerRef = useRef(null);
    const [dropdownWidthPx, setDropdownWidthPx] = useState('auto');
    const showIcon = iconProps?.isShowIcon;
    useEffect(() => {
        const inputContainer = containerRef.current?.querySelector('.ff-input-container');
        if (!inputContainer)
            return;
        const resizeObserver = new ResizeObserver((entries) => {
            for (let entry of entries) {
                const width = `${entry.contentRect.width}px`;
                setDropdownWidthPx(width);
            }
        });
        resizeObserver.observe(inputContainer);
        return () => {
            resizeObserver.disconnect();
        };
    }, []);
    useImperativeHandle(ref, () => inputRef.current);
    useEffect(() => {
        if (cursorPosition !== null && inputRef.current) {
            inputRef.current.setSelectionRange(cursorPosition, cursorPosition);
            inputRef.current.focus();
        }
    }, [cursorPosition]);
    useEffect(() => {
        if (isHash) {
            setShowDropdown(value.startsWith('#'));
        }
        const selectedHashValue = dataFiles?.find((file) => file.name === value);
        const selectedDollarValue = variableList?.find((file) => file?.name === value);
        if (value.startsWith('#') && isHash) {
            const searchQuery = value.slice(1).toLowerCase();
            const filtered = dataFiles.filter((file) => file.name.toLowerCase().includes(searchQuery));
            setFilteredOptions(filtered);
            setShowDropdown(true);
        }
        const isHashSelected = selectedHashValue !== null && value.startsWith('#');
        const isDollarSelected = selectedDollarValue !== null && value.startsWith('$');
        const additionalText = value.length > (selectedDollarValue?.name.length || 0);
        const hasTextWithoutVariable = (value.length > 0 && !isDollarSelected) || value.startsWith('#');
        if (isOnlyHash) {
            setShowCreateVariableIcon(false);
        }
        else {
            if (isDollarSelected ||
                isHashSelected ||
                value.includes('$') ||
                value.includes('#')) {
                setShowCreateVariableIcon(false);
                if (hasTextWithoutVariable) {
                    setShowCreateVariableIcon(true);
                }
            }
            else if (additionalText && !value.includes('$')) {
                setShowCreateVariableIcon(true);
            }
        }
    }, [value]);
    const updateCursorPosition = () => {
        if (inputRef.current) {
            setFindCursor(inputRef.current.selectionStart || 0);
        }
    };
    const handleClick = updateCursorPosition;
    const handleKeyUp = updateCursorPosition;
    useEffect(() => {
        if (inputRef.current) {
            setFindCursor(inputRef.current.selectionStart || 0);
        }
    }, [value]);
    const handleDropdownClick = (item) => {
        if (inputRef.current) {
            const { selectionStart, selectionEnd } = inputRef.current;
            const dollarSyntax = `${item.name}`;
            let newValue;
            if (isHash && value[0] === '#') {
                newValue = item.name + value.slice(selectionEnd || 1);
            }
            else {
                newValue = item.name;
            }
            if (onChange) {
                const event = {
                    target: {
                        value: newValue,
                    },
                };
                onChange(event, item);
                getSelectedVariable(item.name);
            }
            inputRef.current.value = newValue;
            setHashInputValue?.(item);
            setCursorPosition((selectionStart || 0) + dollarSyntax.length);
            setShowDropdown(false);
            setIsDropdownClicked(true);
        }
    };
    function getDropdownState(input, cursorPosit, variableList) {
        let showDropdown = false;
        let searchString = '';
        const checkifCursorPositionhasCloseCurly = value[cursorPosit - 1] === '}';
        if (cursorPosit < 0 || cursorPosit > input.length) {
            return { showDropdown, searchString };
        }
        const lastDollarBeforeCursor = input.lastIndexOf(symbol, cursorPosit - 1);
        const nextDollarAfterCursor = input.indexOf(symbol, cursorPosit);
        if (lastDollarBeforeCursor !== -1) {
            if (isOnlyHash && input[lastDollarBeforeCursor] === '$') {
                showDropdown = false;
            }
            else if (cursorPosit === lastDollarBeforeCursor + 1) {
                showDropdown = true;
                searchString = '';
            }
            else {
                searchString = input.slice(lastDollarBeforeCursor + 1, nextDollarAfterCursor === -1 ? undefined : nextDollarAfterCursor);
                if (cursorPosit > lastDollarBeforeCursor + 1) {
                    searchString = input.slice(lastDollarBeforeCursor + 1, cursorPosit);
                }
                showDropdown = true;
            }
            if (isDropdownClicked && checkifCursorPositionhasCloseCurly) {
                showDropdown = false;
            }
            if (/[{}]/.test(searchString) || cursorPosit === 0) {
                showDropdown = false;
                searchString = '';
            }
            if (searchString) {
                const isInVariableList = variableList.some((file) => file.name.toLowerCase().includes(searchString.toLowerCase()));
                if (!isInVariableList) {
                    variableList = [];
                }
            }
        }
        return { showDropdown, searchString };
    }
    const result = getDropdownState(value, findCursor, variableList);
    const handleBlur = (e) => {
        {
            if (!e.relatedTarget ||
                !e.relatedTarget.closest('.dropdown-container')) {
                setIsFocused(false);
            }
        }
    };
    const variableOptionList = () => {
        return variableList?.filter((file) => file?.name?.toLowerCase()?.includes(result?.searchString?.toLowerCase()));
    };
    const currentIsHash = value.startsWith('#');
    const filteredVariableOptions = currentIsHash
        ? filteredOptions
        : variableOptionList();
    useEffect(() => {
        setHighlightedIndex(0);
    }, [isHash, result?.showDropdown]);
    const handleKeyDown = (e) => {
        switch (e.key) {
            case 'ArrowDown': {
                if (!isFocused)
                    return;
                e.preventDefault();
                e.stopPropagation();
                setHighlightedIndex((prev) => prev < filteredVariableOptions.length - 1 ? prev + 1 : prev);
                break;
            }
            case 'ArrowUp': {
                if (!isFocused)
                    return;
                e.preventDefault();
                e.stopPropagation();
                setHighlightedIndex((prev) => (prev > 0 ? prev - 1 : 0));
                break;
            }
            case 'Enter': {
                if (!isFocused)
                    return;
                e.preventDefault();
                e.stopPropagation();
                if (filteredVariableOptions[highlightedIndex]) {
                    handleDropdownClick(filteredVariableOptions[highlightedIndex]);
                }
                break;
            }
        }
    };
    return (_jsxs("div", { className: "ff-add-variable-container", children: [_jsxs("div", { className: "ff-add-variable-input", ref: containerRef, children: [_jsx(Tooltip, { title: inputTitle, style: { width: '100%' }, children: _jsx(Input, { ...props, name: "add_variable", ref: inputRef, type: type, className: classNames('ff-variable-input-container', {
                                'ff-variable-input-container--show-icon': showIcon,
                            }), value: value, onKeyDown: handleKeyDown, onChange: onChange, onPaste: () => {
                                setShowCreateVariableIcon(true);
                            }, variant: "primary", label: label, placeholder: placeholder, onClick: handleClick, onKeyUp: handleKeyUp, onFocus: () => setIsFocused(true), onBlur: (e) => {
                                handleBlur(e);
                                onBlur?.(e);
                            }, autoComplete: autoComplete, helperText: helperText, error: error, required: required, helperTextWidth: helperTextWidth, ...formProps }) }), !checkEmpty(value) &&
                        showCreateVariableIcon &&
                        showAddVariableIcon && (_jsx("div", { className: "ff-create-variable-container", onClick: onCreateVariableClick, children: _jsx(Typography, { fontWeight: "regular", fontSize: "10px", color: 'var(--brand-color)', cursor: "pointer", children: "Create Variable" }) })), !checkEmpty(value) && !isOnlyHash && (_jsx("div", { className: classNames('ff-cancel-icon-container', {
                            'ff-cancel-icon-container--show-icon': showIcon,
                        }), children: clearIcon && (_jsx(Tooltip, { title: "Cancel", style: { zIndex: 99999 }, children: _jsx(Icon, { onClick: handleClearInput, name: "close", height: 16, width: 16, hoverEffect: true }) })) })), showIcon && (_jsx("div", { className: "ff-info-icon-container", children: _jsx(Tooltip, { title: showIcon && !iconProps?.isIconDisable
                                ? iconProps?.iconToolTipTitle
                                : '', children: _jsx(Icon, { name: iconProps?.iconName || '', hoverEffect: false, height: 16, width: 16, color: iconProps?.iconColor || 'var(--text-area-default-color)', onClick: (e) => {
                                    if (iconProps?.onIconClick) {
                                        iconProps?.onIconClick(e);
                                    }
                                }, disabled: iconProps?.isIconDisable, cursorType: "pointer" }) }) }))] }), result?.showDropdown && isFocused && (_jsx(VariableDropdown, { position: "absolute", zIndex: zIndex, truncateTextValue: truncateTextValue, width: dropdownWidthPx, height: checkEmpty(variableOptionList()) ? 'auto' : dropdownHeight, optionsList: filteredVariableOptions, onSelectVariable: handleDropdownClick, highlightedIndex: highlightedIndex })), showDropdown && isHash && isFocused && (_jsx(OptionsDropdown, { position: "relative", zIndex: zIndex, truncateTextValue: truncateTextValue, width: dropdownWidthPx, filteredOptions: filteredVariableOptions, onSelectVariable: handleDropdownClick, highlightedIndex: highlightedIndex }))] }));
});
export default VariableSuggestionInputDropDown;
//# sourceMappingURL=VariableSuggestionInputDropDown.js.map