import React, { useState } from 'react'
import { apiSaveSettings } from '../api/setttingApi'
import Configuration from '../Configuration'
import Heading from './Heading'
import Loading from './Loading'
import SelectCategories from './SelectCategories'
import settingsHero from '../assets/images/settings-hero.png'

const SettingsTab = () => {
  const [saving, setSaving] = useState(false);
  const [saveError, setSaveError] = useState(false);
  const config = Configuration.getInstance()
  const [categories, setCategories] = useState(config.selectedCategories)
  const [deliveryDays, setDeliveryDays] = useState(config.deliveryDays)
  const handleChangeCategories = categories => {
    setCategories([...categories])
  }
  const handleChangeDeliveryDays = (e) => {
    const value = parseInt(e.target.value, 10)
    setDeliveryDays(isNaN(value) ? 0 : value)
  }
  const handleSaveChanges = (e) => {
    e.preventDefault()
    setSaving(true);
    setSaveError(false);

    apiSaveSettings({
      deliveryDays: deliveryDays,
      categories: categories
    }, () => {
      setSaving(false);
    }, () => {
      setSaving(false);
      setSaveError(true);
    })
  }
  return (
    <div className="dreamfox-tab">
      <Heading text="Settings" />
      <img
        src={settingsHero}
        alt="Delivery date plugin settings"
        className="dreamfox-information__hero"
      />
      <div className="dreamfox-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">
            <input type="number" min="0" value={deliveryDays} onChange={handleChangeDeliveryDays} name="delivery_date[no_of_days_to_deliver]" /><br/>
            <small>How many days user can select delivery date</small>
          </div>
        </div>
        <div className="dreamfox-field">
          <label className="dreamfox-field__label">Applicable Categories</label>
          <small>Select categories for to choose delivery date on checkout</small>
          <SelectCategories defaultValues={categories} onChange={handleChangeCategories}></SelectCategories>
        </div>
        {saving && <Loading message="Saving..." />}
        {!saving && <input className="button-large button-primary" type="button" value="Save Changes" onClick={handleSaveChanges}></input>}
        {saveError && <p className="dreamfox-field__error">Something went wrong while saving. Please try again.</p>}
      </div>
    </div>
  )
}

export default SettingsTab
