import React, { useEffect, useState } from 'react'
import { useDispatch, useSelector } from 'react-redux';
import { apiLoadCommonSettings, apiSaveCommonSettings } from '../../api/commonSetttingApi';
import { loadCommonSettings, updateCommonSetting } from '../../reducers/common-settings';
import Heading from '../Heading'
import Loading from '../Loading';
import SaveButton from '../SaveButton';

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

  const dispatch = useDispatch();
  const loaded = useSelector(state => {
    return state.commonSettings.loaded;
  });
  useEffect(() => {
    if (!loaded) {
      apiLoadCommonSettings(response => {
        dispatch(loadCommonSettings(response));
      });
    }
  }, [loaded]);
  const deliveryDays = useSelector(state => {
    return state.commonSettings.data.deliveryDays;
  });
  const handleChangeDeliveryDays = (e) => {
    dispatch(updateCommonSetting({deliveryDays: e.target.value}, () => {}))
  }
  const handleSaveChanges = (e) => {
    e.preventDefault();
    setSaving(true);
    apiSaveCommonSettings({
      deliveryDays: deliveryDays
    }, response => {
      setSaving(false);
    })
  }
  return (
    <div className="dreamfox-tab">
      <Heading text="Settings" />
      {!loaded && <Loading message="Loading..." />}
      {loaded && <div className="dreamfox-tab__content">
        <div className="dreamfox-field no-of-delivery">
          <label className="dreamfox-field__label">No of day's to Delivery</label>
          <div className="dreamfox-field__content">
            {console.log('deliveryDays: ',deliveryDays)}
            <input type="text" value={deliveryDays} onChange={handleChangeDeliveryDays} /><br/>
            <small>How many days user can select delivery date</small>
          </div>
        </div>
        <SaveButton saving={saving} onClick={handleSaveChanges} />
      </div>}
    </div>
  )
}

export default CommonSettingsTab
