import React from 'react';
import { SelectOptionType } from './interfaces';
import {
  ChipWrapper,
  IconWrapper,
  LabelWrapper,
  SelectMenuWrapper,
  SelectOption,
} from './styles';

type SelectMenuProps = {
  menuPosition?: 'absolute' | 'fixed';
  menuZIndex?: number;
  onOptionClick: (opt: SelectOptionType) => void;
  options: SelectOptionType[];
  wrapperElementRef: React.RefObject<any>;
  selectedOptionLabel?: string;
  selectMenuWidth?: string;
};

const SelectMenu: React.FC<SelectMenuProps> = ({
  menuPosition,
  menuZIndex,
  onOptionClick,
  options,
  wrapperElementRef,
  selectedOptionLabel,
  selectMenuWidth,
}) => {
  const getSelectMenuOptions = () => {
    const wrapperElement = wrapperElementRef.current;

    if (menuPosition == 'absolute' || !wrapperElement) return {};

    const boundingRect = wrapperElement.getBoundingClientRect();
    return {
      fixedPosition: {
        top: boundingRect.top + 48,
        right: window.innerWidth - boundingRect.right,
      },
      selectMenuWidth,
    };
  };
  return (
    <SelectMenuWrapper zIndex={menuZIndex} {...getSelectMenuOptions()}>
      {options.map((opt) => {
        return (
          <SelectOption
            key={opt.label}
            selected={opt.label === selectedOptionLabel}
            onClick={() => onOptionClick(opt)}
          >
            {opt.icon && <IconWrapper>{opt.icon}</IconWrapper>}
            <LabelWrapper>{opt.label}</LabelWrapper>
            {opt.chip && <ChipWrapper>{opt.chip}</ChipWrapper>}
          </SelectOption>
        );
      })}
    </SelectMenuWrapper>
  );
};

export default SelectMenu;
