import trim from 'lodash/trim'

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

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)
    const password = readTrimmedValue(formIds.password)

    if (!isValidPassword(password)) {
      updateFormError(formIds.password, 'error_simple_password')
      isValid = false
    }

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

  return validateForm
}
