import trim from 'lodash/trim'

import { useForm } from 'features/FormStore'
import { isValidPhone } from 'helpers/isValidPhone'

import { formIds } from 'config/form'

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

  const readTrimmedValue = (fieldName: string) => trim(readFormValue(fieldName))

  const validateForm = () => {
    let isValid = true
    const phone = readTrimmedValue(formIds.phone)

    if (phone && !isValidPhone(phone)) {
      updateFormError(formIds.phone, 'error_invalid_phone_format')
      isValid = false
    }
    return isValid
  }

  return validateForm
}
