import { jsxs, jsx, Fragment } from 'react/jsx-runtime';
import React__default, { forwardRef, useContext, useRef, useMemo } from 'react';
import { dropdownDefaultCSSData } from './types.js';
import { checkEmpty } from '../../../utils/checkEmpty/checkEmpty.js';
import Typography from '../../Typography/Typography.js';
import { ThemeContext } from '../../ThemeProvider/ThemeProvider.js';
import classNames from '../../../_virtual/index.js';
import { getValue, getLabel } from '../../../utils/getSelectOptionValue/getSelectOptionValue.js';
import useClickOutside from '../../../hooks/useClickOutside.js';
import Icon from '../../Icon/Icon.js';
import Button from '../../Button/Button.js';
import { useMergeRefs } from '../../../hooks/useMergeRefs.js';
import TruncatedTooltip from '../../TruncatedTooltip/TruncatedTooltip.js';
import { FixedSizeList } from '../../../node_modules/react-window/dist/index.esm.js';

const Dropdown = /*#__PURE__*/forwardRef(({
  options = [],
  optionZIndex = 10000000,
  dropdownPosition,
  labelAccessor,
  onSelectOptionSelector,
  onSelectBlur,
  inputRef,
  selectArrowRef,
  heightFromTop,
  selectedOption,
  valueAccessor,
  showIcon = false,
  customReccurenece = true,
  onCancelModal = () => {},
  onSaveModal = () => {},
  recurrence = false,
  modalJSXProps = jsx(Fragment, {}),
  showArrowIcon = true,
  showClearIcon = false,
  noResultsMessage,
  searchedIcon = ''
}, ref) => {
  const themeContext = useContext(ThemeContext);
  const currentTheme = themeContext?.currentTheme;
  const {
    optionHeight,
    dropDownWrapperPadding
  } = dropdownDefaultCSSData;
  const customRecurrenceOnBlur = customReccurenece ? () => {} : onSelectBlur;
  const optionsWrapperRef = useRef(null);
  const mergedRef = useMergeRefs(optionsWrapperRef, ref);
  useClickOutside(optionsWrapperRef, customRecurrenceOnBlur, [inputRef, selectArrowRef]);
  const {
    positionX,
    positionY,
    fromBottom,
    width
  } = dropdownPosition;
  const {
    margin,
    selectInputHeight
  } = dropdownDefaultCSSData;
  const updateDropdownPosition = () => {
    let dropdownContainerHeight;
    if (checkEmpty(options)) {
      dropdownContainerHeight = 32 + 2 * dropDownWrapperPadding;
    } else if (options?.length > 5) {
      dropdownContainerHeight = 160;
    } else {
      dropdownContainerHeight = options.length * optionHeight + 2 * dropDownWrapperPadding;
    }
    if (fromBottom > dropdownContainerHeight + margin) {
      const dynamicHeightFromTop = heightFromTop <= 25 ? heightFromTop + 7 : heightFromTop <= 32 ? heightFromTop : heightFromTop <= 40 ? heightFromTop - 4 : heightFromTop <= 50 ? heightFromTop - 9 : heightFromTop - 15;
      return {
        left: positionX,
        top: positionY + dynamicHeightFromTop - 10,
        width: showIcon && !checkEmpty(searchedIcon) ? width + 70 : showArrowIcon || showClearIcon ? width + 32 : width + 10,
        zIndex: optionZIndex,
        marginLeft: showIcon && !checkEmpty(searchedIcon) ? '-31px' : '-2px'
      };
    }
    return {
      zIndex: optionZIndex,
      left: positionX,
      width: showIcon ? width + 70 : showArrowIcon ? width + 32 : width + 10,
      top: positionY - selectInputHeight - dropdownContainerHeight + 4 * margin,
      marginLeft: showIcon ? '-29px' : '-2px'
    };
  };
  const positionStyle = updateDropdownPosition();
  const dropdownWidth = positionStyle.width;
  const basePadding = 16;
  const iconPadding = showIcon ? 32 : 0;
  const effectiveContentWidth = customReccurenece ? (typeof dropdownWidth === 'number' ? dropdownWidth / 2 : 0) - basePadding - iconPadding : dropdownWidth - basePadding - iconPadding;
  const sortedOptions = useMemo(() => {
    if (checkEmpty(options)) return [];
    return [...options.filter(option => getValue(option, valueAccessor) === selectedOption), ...options.filter(option => getValue(option, valueAccessor) !== selectedOption)];
  }, [options, selectedOption, valueAccessor]);
  const getOptionLabel = (label, icon, tooltipWidth, iconColor) => {
    if (/*#__PURE__*/React__default.isValidElement(label)) {
      return label;
    }
    return jsxs("div", {
      className: "ff-select-dropdown-option-wrapper",
      children: [showIcon && icon && jsx(Icon, {
        name: icon,
        className: "ff-select-dropdown__icon",
        ...(iconColor && {
          color: iconColor
        })
      }), jsx(Typography, {
        as: "div",
        lineHeight: "25px",
        color: "var(--ff-select-text-color)",
        className: classNames('ff-select-dropdown-text', {
          'ff-select-dropdown-icon-container': showIcon
        }),
        children: jsx(TruncatedTooltip, {
          title: label,
          width: tooltipWidth
        })
      })]
    });
  };
  const onHandleCancelModal = () => {
    onCancelModal();
  };
  const onHandleSaveModal = () => {
    onSelectBlur();
    onSaveModal();
  };
  // Calculate height for virtualization
  const listHeight = useMemo(() => {
    if (checkEmpty(options)) return 32;
    if (options.length > 5) return 160;
    return options.length * optionHeight;
  }, [options]);
  // Render function for virtualized items
  const renderOptionRow = ({
    index,
    style
  }) => {
    const option = sortedOptions[index];
    if (!option) return null;
    const optionValue = getValue(option, valueAccessor);
    const optionLabel = getLabel(option, labelAccessor);
    const iconName = 'iconName' in option ? option.iconName : undefined;
    const iconColor = 'iconColor' in option ? option.iconColor : undefined;
    const isDisabled = 'disable' in option && option.disable;
    return jsx("div", {
      className: classNames('ff-select-dropdown-option', {
        'ff-select-dropdown-option__selected': optionValue === selectedOption
      }, {
        'ff-select-dropdown-option__disabled': isDisabled
      }, currentTheme),
      style: style,
      onClick: () => {
        if (isDisabled) return;
        onSelectOptionSelector(option);
      },
      children: getOptionLabel(optionLabel, iconName, effectiveContentWidth, iconColor)
    }, index);
  };
  return jsxs("div", {
    className: classNames('ff-select-dropdown-wrapper', currentTheme, {
      'ff-select-dropdown-modal-wrapper': recurrence,
      'ff-select-dropdown-mini-modal-wrapper': customReccurenece
    }),
    ref: mergedRef,
    style: positionStyle,
    children: [jsx("div", {
      className: classNames({
        'ff-select-label-minimodal-wrapper': customReccurenece
      }),
      children: !checkEmpty(options) ? jsx("div", {
        style: {
          padding: `${dropDownWrapperPadding}px 0`
        },
        children: jsx(FixedSizeList, {
          height: listHeight,
          width: "100%",
          itemCount: sortedOptions.length,
          itemSize: optionHeight,
          children: renderOptionRow
        })
      }) : jsx(Typography, {
        textAlign: "center",
        as: "div",
        lineHeight: "32px",
        color: "var(--ff-select-text-color)",
        className: classNames('ff-select-no-option', currentTheme),
        children: noResultsMessage || 'No Result Found'
      })
    }), customReccurenece && jsx("div", {
      className: "ff-select-mini-modal-wrapper",
      id: "ff-select-mini-id",
      children: jsxs("div", {
        className: "ff-select-modal-wrapper",
        children: [jsx(Fragment, {
          children: modalJSXProps
        }), jsxs("div", {
          className: "ff-select-mini-modal-footer",
          children: [jsx(Button, {
            label: "Cancel",
            variant: "tertiary",
            onClick: onHandleCancelModal
          }), jsx(Button, {
            label: "Save",
            variant: "secondary",
            onClick: onHandleSaveModal
          })]
        })]
      })
    })]
  });
});

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