import React, { useEffect, useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { apiLoadCategorySettings, apiSaveCategorySettings } from '../../api/categorySettingApi'
import { loadCategorySettings } from '../../reducers/category-settings'
import Heading from '../Heading'
import Loading from '../Loading'
import SaveButton from '../SaveButton'
import SelectCategories from '../SelectCategories'

const CategoriesTab = () => {
  const [saving, setSaving] = useState(false);

  const dispatch = useDispatch();
  const loaded = useSelector(state => {
    return state.categorySettings.loaded;
  });
  useEffect(() => {
    if (!loaded) {
      apiLoadCategorySettings(response => {
        dispatch(loadCategorySettings(response));
      });
    }
  }, [loaded]);
  const categorySettings = useSelector(state => {
    return state.categorySettings.list;
  });
  const handleSaveChanges = (e) => {
    e.preventDefault();
    setSaving(true);
    apiSaveCategorySettings(categorySettings, response => {
      setSaving(false);
    })
  }

  return (
    <div className="dreamfox-tab">
      <Heading text="Categories" />
      {!loaded && <Loading message="Loading..." />}
      {loaded &&
        <div className="dreamfox-tab__content">
          <h3>Applicable Categories</h3>
          <p>Select categories for to choose delivery date on checkout</p>
          <p>-- Set blank &gt;&gt; use global setting.</p>
          <p>-- Set 0 &gt;&gt; For today's delivery date.</p>
          {/* <SelectCategories defaultValues={[]} onChange={handleChangeCategories} /> */}
          <SelectCategories />
          <SaveButton saving={saving} onClick={handleSaveChanges} />
        </div>
      }
    </div>
  )
}

export default CategoriesTab
