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

import { isValidPhone } from 'helpers/isValidPhone'

import { formIds } from 'config/form'

import { useForm } from 'features/FormStore'

export const useUserInfoForm = () => {
  const {
    readFormValue,
    updateFormError,
    updateFormValue,
  } = useForm()

  const onPhoneBlur = useCallback(({ target }: ChangeEvent<HTMLInputElement>) => {
    const phone = target.value
    if (phone && !isValidPhone(phone)) {
      updateFormError(formIds.phone, 'error_invalid_phone_format')
    }
  }, [updateFormError])

  return {
    onPhoneBlur,
    readFormValue,
    updateFormValue,
  }
}
