import React, { useEffect, useState } from 'react'
import Heading from '../Heading'
import DaysForDelivery from '../DaysForDelivery'
import Holidays from '../Holidays'
import WorkingDays from '../WorkingDays'
import SaveButton from '../SaveButton'
import { useDispatch, useSelector } from 'react-redux'
import { apiLoadHolidaySettings, apiSaveHolidaySettings } from '../../api/holidaySettingApi'
import { loadHolidaySettings } from '../../reducers/holiday-settings'
import Loading from '../Loading'

const HolidaysAndWeekendsTab = () => {
  const [saving, setSaving] = useState(false);
  const dispatch = useDispatch()
  const loaded = useSelector(state => {
    return state.holidaySettings.loaded
  })
  useEffect(() => {
    if (!loaded) {
      apiLoadHolidaySettings((response) => {
        dispatch(loadHolidaySettings(response))
      })
    }
  }, [loaded])
  const settings = useSelector(state => {
    return state.holidaySettings
  })
  const handleSaveChanges = (e) => {
    e.preventDefault()
    setSaving(true);
    const { countOnlyWorkingDays, disableDays, holidays } = settings
    apiSaveHolidaySettings({ countOnlyWorkingDays, disableDays, holidays }, response => {
      setSaving(false);
    })
  }
  return (
    <div className="dreamfox-tab">
      <Heading text="Holidays & Weekends" />
      <div className="dreamfox-tab__content">
        <h3>Holidays &amp; Weekends</h3>
        {!loaded && <Loading message="Loading..." />}
        {loaded &&
          <div className="dreamfox-holidays">
            <WorkingDays />
            <DaysForDelivery />
            <Holidays />
            <SaveButton saving={saving} onClick={handleSaveChanges} />
          </div>
        }
      </div>
    </div>
  )
}

export default HolidaysAndWeekendsTab
