import React, { useEffect, useMemo, useState } from "react";
import PropTypes from "prop-types";
import { SubcategoryIcon } from "./SubcategoryChoser.styled";
import FilterRadioDropdown from "../../FilterDropdown/Radio/FilterRadioDropdown";
import { useTranslation } from "react-i18next";

// const firstSubcategoryOption = {
//   label: "SVE PODKATEGORIJE",
//   value: { _id: 0 },
// };

const SubcategoryChoser = (props) => {
  const filters = props.filters;
  const { t } = useTranslation();
  const [isOpened, setIsOpened] = useState(false);
  const [isDisabled, setIsDisabled] = useState(true);
  const subcategories = useMemo(() => {
    return filters.category.getSubcategories(
      filters.category.selectedCategoryLocally?.name
    );
  }, [filters.category.selectedCategoryLocally]);

  useEffect(() => {
    if (!filters.category.selectedCategoryLocally || filters.category.selectedCategoryLocally?._id === 0) {
      setIsOpened(false);
      setIsDisabled(true);
    } else {
      setIsDisabled(false);
      setIsOpened(true);
    }
  }, [filters.category.selectedCategoryLocally]);

  const handleOpen = () => {
    setIsOpened((prevState) => !prevState);
  };

  console.log(filters);

  return (
    <FilterRadioDropdown
      data={subcategories}
      icon={<SubcategoryIcon />}
      title={
        filters.subcategory.selectedSubcategory?.name
          ? filters.subcategory.selectedSubcategory?.name
          : t("filters.subcategories.title")
      }
      searchPlaceholder={t("filters.subcategories.placeholder")}
      setSelected={filters.subcategory.setSelectedSubcategory}
      selected={filters.subcategory.selectedSubcategoryLocally}
      open={isOpened}
      disabled={isDisabled}
      handleOpen={handleOpen}
      firstOption={filters.subcategory.initialOption}
    />
  );
};

SubcategoryChoser.propTypes = {
  filters: PropTypes.any,
};

export default SubcategoryChoser;
