import { useState, ChangeEvent } from 'react'
import { set, cloneDeep } from 'lodash'

export function useForm<T extends Dict>(initialValues: T) {
  const [values, setValues] = useState(initialValues)

  const touched = Object.entries(initialValues)
    .filter(([key, value]) => value !== values[key])
    .map(([key]) => key)

  function loadData(values: T) {
    setValues(values)
  }

  function onChange(
    event:
      | ChangeEvent<HTMLInputElement>
      | ChangeEvent<HTMLSelectElement>
      | CustomChangeEvent
  ) {
    const { type, name, value } = event.target
    const newValue =
      type === 'checkbox'
        ? (event.target as EventTarget & HTMLInputElement).checked
        : value

    if (name.includes('.')) {
      const copy = cloneDeep(values)
      set(copy, name, newValue)
      setValues(copy)
    } else {
      setValues({ ...values, [name]: newValue })
    }
  }

  return { values, touched, onChange, loadData }
}
