import KeyboardArrowDownIcon from "@mui/icons-material/KeyboardArrowDown";
import KeyboardArrowUpIcon from "@mui/icons-material/KeyboardArrowUp";
import PropTypes from "prop-types";
import React, { useRef } from "react";
import Picker from "react-scrollable-picker";
import {
  StyledArrowWrapper,
  StyledRadioButtonUncheckedIcon,
  Wrapper,
} from "./styles";

const SelectPicker = ({
  optionGroups = {},
  valueGroups = {},
  onChange,
  color = "#000000",
  size = "medium",
  ...others
}) => {
  const cardWrapperRef = useRef(null);
  const handleOnClickPickerDirection = (direction) => {
    //select all the elements with .picker-item class
    const pickerItems = cardWrapperRef.current.querySelectorAll(".picker-item");

    let index = 0;
    pickerItems.forEach((el, _index) => {
      //finds the index of the selected picker
      if (el.classList.contains("picker-item-selected")) index = _index;
    });

    //Trigger on click event depending on the direction
    if (direction === "up" && index < pickerItems.length - 1)
      pickerItems[index + 1].click();

    if (direction === "down" && index > 0) pickerItems[index - 1].click();
  };
  return (
    <Wrapper ref={cardWrapperRef} color={color} size={size}>
      <StyledRadioButtonUncheckedIcon customcolor={color} />
      <Picker
        {...others}
        optionGroups={optionGroups}
        valueGroups={valueGroups}
        onChange={onChange}
        itemHeight={size === "medium" ? 20 : 15}
        height={size === "medium" ? 40 : 30}
      />
      <StyledArrowWrapper>
        <KeyboardArrowUpIcon
          onClick={(e) => {
            e.stopPropagation();
            handleOnClickPickerDirection("up");
          }}
        />
        <KeyboardArrowDownIcon
          onClick={(e) => {
            e.stopPropagation();
            handleOnClickPickerDirection("down");
          }}
        />
      </StyledArrowWrapper>
    </Wrapper>
  );
};

SelectPicker.propTypes = {
  optionGroups: PropTypes.object.isRequired,
  valueGroups: PropTypes.object.isRequired,
  onChange: PropTypes.func,
  color: PropTypes.string,
  size: PropTypes.oneOfType(["small", "medium"]),
};

export default SelectPicker;
