import React, { useEffect, useState } from "react";
import PropTypes from "prop-types";
import DropdownItem from "../../../../Dropdown/DropdownItem/DropdownItem";
import CheckboxDropdownList from "./CheckboxDropdownList/CheckboxDropdownList";
import Checkbox from "./Checkbox/Checkbox";

const FilterCheckboxDropdown = (props) => {
  const [dataToShow, setDataToShow] = useState([]);
  const [isOpened, setIsOpened] = useState(false);
  const [toSearch, setToSearch] = useState("");
  const { data } = props;

  useEffect(() => {
    setDataToShow([...data]);
  }, [data]);

  useEffect(() => {
    if (toSearch.length > 0) {
      setDataToShow(
        data.filter((item) =>
          item.city.toLowerCase().includes(toSearch.toLowerCase())
        )
      );
    } else {
      setDataToShow([...data]);
    }
  }, [toSearch]);

  useEffect(() => {
    if (props.filters?.length > 0) {
      setIsOpened(true);
    }
  }, [props.filters]);

  const handleChange = (item) => {
    if (props.oneValueAllowed) {
      props.setItemsSelected([item]);
    } else {
      if (
        props.filters.find(
          (itemInList) =>
            itemInList?.city?.toString() === item?.city?.toString()
        )
      ) {
        props.setItemsSelected([
          ...props.filters.filter(
            (p) => p?.city?.toString() !== item?.city?.toString()
          ),
        ]);
      } else {
        props.setItemsSelected([...props.filters, item]);
      }
    }
  };

  return (
    <CheckboxDropdownList
      toSearch={toSearch}
      setToSearch={setToSearch}
      title={props.title}
      filters={props.filters}
      icon={props.icon}
      data={data}
      searchPlaceholder={props.searchPlaceholder}
      isOpened={isOpened}
      setIsOpened={setIsOpened}
      setItemsSelected={props.setItemsSelected}
    >
      {dataToShow.map((item) => {
        return (
          <DropdownItem key={item.city}>
            <Checkbox
              item={item}
              filters={props.filters}
              onChange={() => handleChange(item)}
            />
          </DropdownItem>
        );
      })}
    </CheckboxDropdownList>
  );
};

FilterCheckboxDropdown.propTypes = {
  children: PropTypes.node,
  icon: PropTypes.node,
  data: PropTypes.array,
  title: PropTypes.string,
  oneValueAllowed: PropTypes.bool,
  searchPlaceholder: PropTypes.string,
  setItemsSelected: PropTypes.func,
  filters: PropTypes.array,
};
FilterCheckboxDropdown.defaultProps = {
  oneValueAllowed: false,
};
export default FilterCheckboxDropdown;
