import { jsxs, jsx } from 'react/jsx-runtime';
import { forwardRef, useState, useRef, useImperativeHandle, useEffect } from 'react';
import { checkEmpty } from '../../utils/checkEmpty/checkEmpty.js';
import VariableDropdown from '../Editor/VariableDropdown.js';
import Icon from '../Icon/Icon.js';
import Input from '../Input/Input.js';
import OptionsDropdown from './OptionsDropdown.js';
import Tooltip from '../Tooltip/Tooltip.js';
import Typography from '../Typography/Typography.js';

const ConditionalDropdown = forwardRef(({ label = '', hashInputValue = '', setHashInputValue, variableList = [], addForloopPrefix = false, placeholder = 'Enter text', onChange, onCreateVariableClick, value = '', dropdownWidth = 'inherit', isHash = false, dataFiles = [], showAddVariableIcon = true, helperText = '', error, autoComplete = 'off', showHidePasswordIcon = true, required = false, formProps = {}, onlyDropdown = false, type, onFocus, onBlur, readOnly = false, height = '160px', truncateTextValue = 34, isTruncateText = false, ...props }, ref) => {
    const [showDropdown, setShowDropdown] = useState(false);
    const [isDropdownClicked, setIsDropdownClicked] = useState(false);
    const [isFocused, setIsFocused] = useState(false);
    const [cursorPosition, setCursorPosition] = useState(null);
    const [findCursor, setFindCursor] = useState(0);
    const [skipEffect, setSkipEffect] = useState(false);
    const [showCreateVariableIcon, setShowCreateVariableIcon] = useState(false);
    const [filteredOptions, setFilteredOptions] = useState([]);
    const inputRef = useRef(null);
    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('#'));
        }
        else {
            setShowCreateVariableIcon(!value?.includes('$'));
        }
        if (value.startsWith('#') && isHash) {
            const searchQuery = value.slice(1).toLowerCase();
            const filtered = dataFiles.filter((file) => file.name.toLowerCase().includes(searchQuery));
            setFilteredOptions(filtered);
            setShowDropdown(true);
        }
    }, [value]);
    useEffect(() => {
        if (!skipEffect && onlyDropdown) {
            const filteredResults = dataFiles
                .filter((item) => item.toLowerCase().includes(value.toLowerCase()))
                .map((item, index) => ({
                id: index + 1,
                name: item,
            }));
            setFilteredOptions(filteredResults);
            setShowDropdown(filteredResults.length > 0);
        }
        setSkipEffect(false);
    }, [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]);
    function findNearestDollar(input, cursorPosition) {
        const lastDollarBeforeCursor = input.lastIndexOf('$', cursorPosition - 1);
        const nextDollarAfterCursor = input.indexOf('$', cursorPosition);
        if (lastDollarBeforeCursor === -1 && nextDollarAfterCursor === -1) {
            return -1;
        }
        else if (lastDollarBeforeCursor === -1) {
            return nextDollarAfterCursor;
        }
        else if (nextDollarAfterCursor === -1) {
            return lastDollarBeforeCursor;
        }
        else {
            return Math.abs(cursorPosition - lastDollarBeforeCursor) <=
                Math.abs(nextDollarAfterCursor - cursorPosition)
                ? lastDollarBeforeCursor
                : nextDollarAfterCursor;
        }
    }
    const handleDropdownClick = (item) => {
        if (inputRef.current) {
            const { selectionStart, selectionEnd } = inputRef.current;
            const dollarSyntax = `{${item.parentVariableType === 'STEPGROUP'
                ? 'SGV'
                : item.type === 'LOCAL'
                    ? 'LV'
                    : item.type === 'GLOBAL'
                        ? 'GV'
                        : item.type === 'GROUP'
                            ? 'SGV'
                            : [String(item?._id ?? ''), String(item?.id ?? '')].some((val) => val.includes('PARAMETER'))
                                ? 'SGP'
                                : item.type === '_startforloop'
                                    ? 'FLV_for:'
                                    : item.type === 'DATAPROVIDER'
                                        ? 'DPV'
                                        : 'PEV'}${item?.type === '_startforloop' ? '' : '_'}${item?.type === 'DATAPROVIDER'
                ? item?.dpName + ':' + item?.varname
                : item.name}}`;
            let newValue;
            if ((isHash && value[0] === '#') || (onlyDropdown && !item?.type)) {
                newValue = item.name + value.slice(selectionEnd || 1);
            }
            else {
                newValue =
                    value.slice(0, findNearestDollar(value, findCursor) || 0) +
                        '$' +
                        dollarSyntax +
                        value.slice(selectionEnd || 0);
            }
            if (onChange) {
                const event = {
                    target: {
                        value: newValue,
                    },
                };
                onChange(event, item);
            }
            inputRef.current.value = newValue;
            setHashInputValue?.(item);
            setCursorPosition((selectionStart || 0) + dollarSyntax.length);
            setShowDropdown(false);
            setSkipEffect(true);
            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('$', cursorPosit - 1);
        const nextDollarAfterCursor = input.indexOf('$', cursorPosit);
        if (lastDollarBeforeCursor !== -1) {
            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) => {
                    const searchableName = file.type === '_startforloop' && addForloopPrefix
                        ? `FLV_for:${file.name}`
                        : file.name;
                    return searchableName
                        .toLowerCase()
                        .includes(searchString.toLowerCase());
                });
                if (!isInVariableList) {
                    showDropdown = false;
                    searchString = '';
                }
            }
        }
        return { showDropdown, searchString };
    }
    const result = getDropdownState(value, findCursor, variableList);
    const handleBlur = (e) => {
        {
            if (!e.relatedTarget ||
                !e.relatedTarget.closest('.dropdown-container')) {
                setIsFocused(false);
            }
        }
    };
    const [showPassword, setShowPassword] = useState(false);
    const togglePasswordVisibility = () => {
        setShowPassword((prev) => !prev);
    };
    const getInputType = (type, showPassword) => {
        if (type === 'password') {
            return showPassword ? 'text' : 'password';
        }
        return type ?? 'text';
    };
    return (jsxs("div", { className: "ff-add-variable-container", children: [jsxs("div", { className: "ff-add-variable-input", children: [jsx(Input, { readOnly: readOnly, ...props, name: "add_variable", ref: inputRef, type: getInputType(type, showPassword), value: value, onChange: onChange, variant: "primary", label: label, placeholder: placeholder, onClick: handleClick, onKeyUp: handleKeyUp, onFocus: (e) => {
                            setTimeout(() => {
                                setIsFocused(true);
                                onFocus?.(e);
                            }, 500);
                        }, onBlur: (e) => {
                            handleBlur(e);
                            onBlur?.(e);
                        }, autoComplete: autoComplete, helperText: helperText, error: error, required: required, ...formProps }), type === 'password' && showHidePasswordIcon && (jsx(Tooltip, { title: showPassword ? 'Hide' : 'Show', children: jsx(Typography, { as: "span", className: "ff-password-icon", children: jsx(Icon, { onClick: togglePasswordVisibility, name: !showPassword ? 'view_access_icon' : 'hide_access_icon', width: 16, height: 16, hoverEffect: true }) }) })), !checkEmpty(value) &&
                        !isHash &&
                        showCreateVariableIcon &&
                        showAddVariableIcon && (jsx(Tooltip, { title: "Add Variable", children: jsx(Icon, { onClick: onCreateVariableClick, name: "add_variable", width: 24, height: 24, hoverEffect: true }) }))] }), result?.showDropdown && isFocused && (jsx(VariableDropdown, { position: "absolute", width: dropdownWidth, optionsList: variableList.filter((file) => {
                    const searchableName = file.type === '_startforloop' && addForloopPrefix
                        ? `FLV_for:${file.name}`
                        : file.name;
                    return searchableName
                        .toLowerCase()
                        .includes(result?.searchString.toLowerCase());
                }), onSelectVariable: handleDropdownClick, height: height })), showDropdown && (isHash || onlyDropdown) && (jsx(OptionsDropdown, { position: "relative", width: dropdownWidth, filteredOptions: filteredOptions, zIndex: 2000, onSelectVariable: handleDropdownClick, height: height, isTruncateText: isTruncateText, truncateTextValue: truncateTextValue }))] }));
});

export { ConditionalDropdown as default };
//# sourceMappingURL=ConditionalDropdown.js.map
