/* FileName: CustomDropdown.tsx
 *  Description: The CustomDropdown component is a dropdown menu for selecting an option.
 *  It is a wrapper for the react-select package.
*/
import React, { useEffect, useRef, useState } from 'react';
import Select from 'react-select';

const CustomDropdown: React.FC<any> = ({
    isDisabled = false,
    openMenuOnFocus = false,
    value,
    onChange,
    onInputChange,
    getOptionLabel,
    getOptionValue,
    options = [],
    isSearchable = true,
    isClearable = false,
    className = '',
    styles = {},
    ...rest
}) => {
    //use for scroll to selected option
    const [menuIsOpen, setMenuIsOpen] = useState(false);
    const [highlightedIndex, setHighlightedIndex] = useState(0);
    const selectWrapperRef = useRef<HTMLDivElement>(null);

    useEffect(() => {
        if (menuIsOpen) {
            // Delay scroll to allow menu to render
            setTimeout(() => {
                const selectedOption = document.querySelector(
                    '.react-select__menu .react-select__option--is-selected'
                );
                if (selectedOption) {
                    // selectedOption.scrollIntoView({ block: 'center' });
                }
            }, 0);
        }
    }, [menuIsOpen]);

    return (
        <div className={`DropdownMainBox h-full ${className ? className : ''}`} ref={selectWrapperRef} >
            {/* react-select package component */}
            <Select
                isDisabled={isDisabled}
                openMenuOnFocus={openMenuOnFocus}
                value={value}
                onChange={onChange}
                onInputChange={onInputChange}
                getOptionLabel={getOptionLabel}
                getOptionValue={getOptionValue}
                options={options}
                isSearchable={isSearchable}
                isClearable={isClearable}
                classNamePrefix="react-select"
                className={`customDropdown h-full shrink-0 ${className}`}
                styles={styles}
                // menuIsOpen={}
                onMenuOpen={() => setMenuIsOpen(true)}
                onMenuClose={() => setMenuIsOpen(false)}
                {...rest}
            />
        </div>
    );
};

export default CustomDropdown;
