import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { forwardRef, useContext, useEffect, useMemo, useState } from 'react';
import { dropdownDefaultCSSData } from './dropdownTypes';
import './Dropdown.scss';
import { ThemeContext } from '../ThemeProvider/ThemeProvider';
import classNames from 'classnames';
import Button from '../Button';
import Typography from '../Typography';
import Checkbox from '../Checkbox';
import Tooltip from '../Tooltip';
import { isTextTruncated, truncateText, } from '../../utils/truncateText/truncateText';
import { getLabel, getValue, } from '../../utils/getSelectOptionValue/getSelectOptionValue';
import { useIntersectionObserver } from '../../hooks/useIntersectionObserver';
import { useKeyboardActions } from '../../utils/keyBoardActionUtil/UseKeyboardActions';
import { ALPHA_NUM_EXTENDED_REGEX, START_END_WHITESPACE_REGEX, } from '../../validations/regex';
import { ffid } from '../../utils/ffID/ffid';
const Dropdown = forwardRef(({ options, handleOptionChange, searchedKeyword = '', dropdownPosition = {}, zIndex, withSelectButton, labelAccessor = 'label', valueAccessor = 'value', searchAccessor = valueAccessor, loadMoreOptions, isAllSelected, onToggleAllSelect, isAllSelect, maxDropdownHeight: _maxDropdownHeight, variant, handleIconClick, noResultsMessage, maxSearchCharacterLength = 25, }, ref) => {
    const [focusedIndex, setFocusedIndex] = useState(null);
    const [validationError, setValidationError] = useState(null);
    const [selectDisable, setSelectDisable] = useState(true);
    const filteredOptions = options
        ? options.filter((option) => getValue(option, searchAccessor)
            ?.toLowerCase()
            .includes(searchedKeyword.trim().toLowerCase()))
        : [];
    const { verticalMargin, optionHeight, maxDropdownHeight } = dropdownDefaultCSSData;
    useEffect(() => {
        if (variant !== 'labels')
            return;
        switch (true) {
            case searchedKeyword.length < 3 && searchedKeyword.trim() !== '':
                setValidationError('Minimum 3 characters required');
                break;
            case !!searchedKeyword &&
                !START_END_WHITESPACE_REGEX.test(searchedKeyword):
                setValidationError('Space is not allowed at starting and at the end');
                break;
            case !!searchedKeyword &&
                !ALPHA_NUM_EXTENDED_REGEX.test(searchedKeyword):
                setValidationError('Name should be alphanumeric');
                break;
            case searchedKeyword.length > maxSearchCharacterLength:
                setValidationError(`Maximum ${maxSearchCharacterLength} characters allowed`);
                break;
            default:
                setValidationError(null);
        }
    }, [searchedKeyword, variant, maxSearchCharacterLength]);
    useEffect(() => {
        const hasChecked = filteredOptions.some((option) => option.isChecked === true && !option.isDisabled);
        setSelectDisable(!hasChecked);
    }, [filteredOptions]);
    const onSelectClick = (e) => {
        e.stopPropagation();
        handleOptionChange({}, false);
    };
    const renderOption = (info, labelAccessor) => {
        if (typeof info[labelAccessor] === 'string') {
            return truncateText(getLabel(info, labelAccessor), dropdownPosition.width - 50, 'pixel');
        }
        return info[labelAccessor];
    };
    const topPosition = useMemo(() => {
        let calculatedDropdownHeight = Math.min(filteredOptions.length * optionHeight, _maxDropdownHeight || maxDropdownHeight);
        if (filteredOptions.length < 5 && withSelectButton) {
            calculatedDropdownHeight += 32;
        }
        const isEnoughSpaceAvailable = dropdownPosition.fromBottom >=
            calculatedDropdownHeight + verticalMargin;
        const topPosition = isEnoughSpaceAvailable
            ? dropdownPosition.top
            : dropdownPosition.top -
                calculatedDropdownHeight -
                dropdownPosition.selectHeight -
                2 * verticalMargin;
        return topPosition;
    }, [filteredOptions.length, withSelectButton, dropdownPosition]);
    const themeContext = useContext(ThemeContext);
    const currentTheme = themeContext?.currentTheme;
    useIntersectionObserver(['ff-multiselect-pagination'], {
        root: document.getElementById('ff-multiselect-options-wrapper'),
        rootMargin: '0px',
        threshold: 0.1,
        onIntersect: (entry, _observer) => {
            if (entry.isIntersecting) {
                if (loadMoreOptions) {
                    loadMoreOptions();
                }
            }
        },
    });
    useKeyboardActions([
        {
            key: 'ArrowDown',
            action: () => {
                setFocusedIndex((prev) => prev === null ? 0 : (prev + 1) % filteredOptions.length);
            },
        },
        {
            key: 'ArrowUp',
            action: () => {
                setFocusedIndex((prev) => prev === null
                    ? filteredOptions.length - 1
                    : (prev - 1 + filteredOptions.length) % filteredOptions.length);
            },
        },
        {
            key: 'Enter',
            action: () => {
                if (focusedIndex !== null) {
                    handleOptionChange(filteredOptions[focusedIndex], !filteredOptions[focusedIndex]?.isChecked);
                }
                else {
                    withSelectButton && !selectDisable && handleOptionChange({}, false);
                }
            },
        },
    ]);
    useEffect(() => {
        if (focusedIndex !== null) {
            const optionElement = document.querySelector(`.dropdown-option-container:nth-child(${focusedIndex + 1})`);
            if (optionElement) {
                optionElement.scrollIntoView({
                    behavior: 'smooth',
                    block: 'nearest',
                });
            }
        }
    }, [focusedIndex]);
    return (_jsxs("div", { role: "listbox", ref: ref, className: classNames('ff-multiselect-dropdown-container', {
            [currentTheme || '']: true,
        }), style: {
            left: dropdownPosition.left,
            top: topPosition,
            width: dropdownPosition.width,
            zIndex,
            maxHeight: `${_maxDropdownHeight}px`,
        }, children: [_jsx("div", { className: "ff-multiselect-options-wrapper", style: {
                    maxHeight: withSelectButton
                        ? `${_maxDropdownHeight - 32}px`
                        : `${_maxDropdownHeight}px`,
                }, id: "ff-multiselect-options-wrapper", children: validationError ? (_jsx(Typography, { as: "p", className: "validation-error", children: validationError })) : filteredOptions.length === 0 ? (variant === 'labels' && searchedKeyword.trim().length > 2 ? (_jsxs(Typography, { as: "p", className: "no-options", onClick: handleIconClick, children: [searchedKeyword, ' ', _jsx(Typography, { as: "span", color: 'var(--brand-color)', children: "add label" })] })) : (_jsx(Typography, { textAlign: "center", as: "p", className: "no-options", children: noResultsMessage || 'No Result Found' }))) : (_jsxs(_Fragment, { children: [isAllSelect && (_jsxs("div", { className: "dropdown-option-container", children: [_jsx(Checkbox, { checked: isAllSelected, onChange: (event) => {
                                        onToggleAllSelect?.(event.target.checked);
                                    } }), _jsx(Typography, { className: "dropdown-option-label", children: "All" })] })), filteredOptions.map((info, index) => (_jsxs("div", { role: "option", className: `dropdown-option-container${info.isDisabled ? ' disabled' : ''} ${focusedIndex === index ? 'focused' : ''}`, onMouseEnter: () => setFocusedIndex(null), onClick: (e) => {
                                const target = e.target;
                                if (target.type === 'checkbox') {
                                    return;
                                }
                                !info?.isDisabled &&
                                    handleOptionChange(info, !info.isChecked);
                            }, children: [_jsx(Checkbox, { checked: info.isChecked, disabled: info?.isDisabled }), _jsx(Tooltip, { zIndex: zIndex + 1, title: isTextTruncated(getLabel(info, labelAccessor), dropdownPosition.width - 50, 'pixel')
                                        ? getLabel(info, labelAccessor)
                                        : '', children: _jsx(Typography, { className: "dropdown-option-label", children: renderOption(info, labelAccessor) }) })] }, getLabel(info, labelAccessor) + ffid()))), _jsx("div", { id: "ff-multiselect-pagination" })] })) }), withSelectButton && filteredOptions.length > 0 && (_jsx("div", { className: "select-button-container", children: _jsx(Button, { label: "Select", variant: "primary", onClick: onSelectClick, disabled: selectDisable, buttonWidth: "100%", buttonHeight: "24px" }) }))] }));
});
export default Dropdown;
//# sourceMappingURL=Dropdown.js.map