import React, { useState } from "react";
import PropTypes from "prop-types";
import {
  SelectWrapper,
  Dropdown,
  DropdownItem,
  SearchInput,
  Label,
  Icon,
} from "./styles";

/**
 * @param {{
* dropdownData: Array,
* header: string,
* searchable: boolean,
* className: string,
* onSelect: Function,
* inputPlaceHolder: string,
* size: string,
* }} props - properties of the dropdown component
*/

const Select = ({
  onSelect,
  dropdownData,
  searchable,
  inputPlaceholder,
  borderRadius,
  size,
  label,
  color,
  animate,
  bordered,
}) => {
  const [isOpen, setIsOpen] = useState(false);
  const [searchTerm, setSearchTerm] = useState("");
  const [filteredData, setFilteredData] = useState(dropdownData);

  const handleSelect = (selectedValue) => {
    onSelect(selectedValue);
    setIsOpen(false);
    setSearchTerm(
      dropdownData.find((item) => item.value === selectedValue).name
    );
  };

  const handleSearch = (searchValue) => {
    setSearchTerm(searchValue);
  };

  const handleClickIcon = () => {
    setIsOpen(!isOpen);
  };

  return (
    <SelectWrapper>
      <Label size={size} color={color}>
        {label}
      </Label>
      <SearchInput
        bordered={bordered}
        searchable={searchable}
        size={size}
        color={color}
        borderRadius={borderRadius}
        type="text"
        placeholder={inputPlaceholder}
        value={searchTerm}
        onChange={(e) => handleSearch(e.target.value)}
        onFocus={() => setIsOpen(true)}
      />
      <Icon size={size} color={color} onClick={handleClickIcon} />
      {isOpen && (
        <Dropdown borderRadius={borderRadius} animate={animate}>
          {filteredData.map(({ value, name }, index) => (
            <DropdownItem
              key={value}
              size={size}
              color={color}
              onClick={() => handleSelect(value)}
              active={name?.toLowerCase() === searchTerm.toLowerCase()}
            >
              {name}
            </DropdownItem>
          ))}
        </Dropdown>
      )}
    </SelectWrapper>
  );
};

Select.propTypes = {
  onSelect: PropTypes.func.isRequired,
  dropdownData: PropTypes.arrayOf(
    PropTypes.shape({
      value: PropTypes.string.isRequired,
      name: PropTypes.string.isRequired,
    })
  ).isRequired,
  searchable: PropTypes.bool,
  inputPlaceholder: PropTypes.string,
  borderRadius: PropTypes.string,
  size: PropTypes.number,
  label: PropTypes.string,
  color: PropTypes.string,
  animate: PropTypes.bool,
  bordered: PropTypes.bool,
};

Select.defaultProps = {
  searchable: false,
  inputPlaceholder: "",
  borderRadius: "3px",
  size: 16,
  label: "",
  color: "",
  animate: false,
  bordered: false,
};

export default Select;
