import React from 'react'
import { useDispatch } from 'react-redux'
import { updateCategorySetting } from '../reducers/category-settings'

const SelectCategoriesItem = ({item}) => {
  const elementId = 'dreamfox-field-'+item.id
  const dispatch = useDispatch()
  const handleDaysChanged = (e) => {
    const raw = e.target.value
    const days = raw === '' ? null : parseInt(raw, 10)
    dispatch(updateCategorySetting({id: item.id, data: {days: isNaN(days) ? null : days}}))
  }
  const handleCheckClick = e => {
    dispatch(updateCategorySetting({id: item.id, data: {selected: e.target.checked}}))
  }
  return (
    <div className="dreamfox-select-categories-item">
      <div className="dreamfox-select-categories-item__check">
        <input
          className="dreamfox-select-categories-item__input"
          type="checkbox"
          checked={item.selected}
          id={elementId}
          onChange={handleCheckClick}
        />
        <label className="dreamfox-select-categories-item__label" htmlFor={elementId}>{item.name}</label>
      </div>
      <div>
        <input type="number" min="0" className="dreamfox-select-categories-item__number" value={item.days == null ? '' : item.days} onChange={handleDaysChanged} />
      </div>
    </div>
  )
}

export default SelectCategoriesItem
