import { forwardRef, useContext } from 'react';
import { dropdownDefaultCSSData, DropdownProps } from './dropdownTypes';

import './Dropdown.scss';
import { ThemeContext } from '../ThemeProvider/ThemeProvider';
import classNames from 'classnames';

const Dropdown = forwardRef<HTMLDivElement, DropdownProps>(
  (
    {
      options,
      handleOptionChange,
      searchedKeyword = '',
      dropdownPosition = {},
      zIndex,
    },
    ref
  ) => {
    const filteredOptions = options
      ? options.filter((option) =>
          option.label?.toLowerCase().includes(searchedKeyword.toLowerCase())
        )
      : [];
    const { verticalMargin, optionHeight, maxDropdownHeight } =
      dropdownDefaultCSSData;
    const dropdownHeight = Math.min(
      filteredOptions.length * optionHeight,
      maxDropdownHeight
    );
    const isEnoughBottomSpaceAvailable =
      dropdownPosition.fromBottom >= dropdownHeight + verticalMargin;

    const topPosition = isEnoughBottomSpaceAvailable
      ? dropdownPosition.top
      : dropdownPosition.top -
        dropdownHeight -
        dropdownPosition.selectHeight -
        2 * verticalMargin;
    const themeContext = useContext(ThemeContext);
    const currentTheme = themeContext?.currentTheme;
    return (
      <div
        role="listbox"
        ref={ref}
        className={classNames('ff-multiselect-dropdown-container', {
          [currentTheme || '']: true,
        })}
        style={{
          left: dropdownPosition.left,
          top: topPosition,
          width: dropdownPosition.width,
          zIndex,
        }}
      >
        {filteredOptions.length === 0 ? (
          <div className="dropdown-option-container">
            <p className="no-options">No Option</p>
          </div>
        ) : (
          filteredOptions.map((info) => (
            <div
              role="option"
              className={`dropdown-option-container`}
              key={info.label}
              onClick={() => handleOptionChange(info, !info.isChecked)}
            >
              <input type="checkbox" checked={info.isChecked} readOnly />
              <span className="dropdown-option-label">{info.label}</span>
            </div>
          ))
        )}
      </div>
    );
  }
);

export default Dropdown;
