import type { ChangeEvent } from 'react'
import { useState } from 'react'

import isNaN from 'lodash/isNaN'

import type { EpisodeDuration } from '../../types'

const LIMITS = {
  max: 30,
  min: 1,
}

const isValidDuration = (value: number) => (
  isFinite(value)
  && value >= LIMITS.min
  && value <= LIMITS.max
)

export type Props = {
  onChange: (duration: EpisodeDuration) => void,
  value: EpisodeDuration,
}

export const useInputHandlers = ({ onChange, value: initialValue }: Props) => {
  const [duration, setDuration] = useState(initialValue)
  const handleChange = (key: 'before' | 'after') => (
    (e: ChangeEvent<HTMLInputElement>) => {
      const seconds = Number(e.target.value)
      setDuration({
        ...duration,
        [key]: isNaN(seconds) ? '' : seconds,
      })
    }
  )

  const handleBlur = () => {
    const { after, before } = duration
    if (isValidDuration(before) && isValidDuration(after)) {
      onChange(duration)
    } else {
      setDuration(initialValue)
    }
  }
  return {
    duration,
    handleBlur,
    handleChange,
  }
}
