import React, { useEffect, useState } from 'react'
import { useDispatch, useSelector } from 'react-redux';
import { apiLoadCategories } from '../api/setttingApi';
import { loadAllCategories } from '../reducers/category-list';
import Loading from './Loading'
import SelectCategoriesItem from './SelectCategoriesItem';

const SelectCategories = ({defaultValues, onChange}) => {
  const dispatch = useDispatch();
  const loaded = useSelector(state => {
    return state.categories.loaded;
  });
  const [selectedCategories, setSelectedCategories] = useState(
    (defaultValues || []).map(Number)
  );
  useEffect(() => {
    if (!loaded) {
      apiLoadCategories((response) => {
        dispatch(loadAllCategories(response.data['categories']));
      });
    }
  }, [loaded]);
  const categories = useSelector(state => {
    return state.categories.list;
  });
  const handleChangeCategories = (categoryId, checked) => {
    const numericId = Number(categoryId)
    let newCategories = []
    if (checked) {
      newCategories = [...selectedCategories, numericId]
    } else {
      newCategories = selectedCategories.filter(element => element !== numericId);
    }
    setSelectedCategories(newCategories);

    onChange(newCategories)
  }
  return (
    <div className="dreamfox-select-categories">
      {!loaded && <Loading message="Loading..."></Loading>}
      {loaded &&
        categories && categories.map(category => {
          const numericValue = Number(category.value)
          return (<SelectCategoriesItem
            key={numericValue}
            checked={selectedCategories.includes(numericValue)}
            onChange={handleChangeCategories}
            category={category} />)
        })
      }
    </div>
  )
}

export default SelectCategories
