function FormValidation () {
  function fieldHasError (field) {
    for (const error in field.validity) {
      if (field.validity[error] && !field.validity.valid) {
        return error
      }
    }

    return false
  }

  function getCustomMessage (field, errorType) {
    const valueMissing = 'Campo obrigatório'
    const tooShort = `Campo deve ter pelo menos ${field.minLength} caracteres`
    const messages = {
      text: {
        valueMissing,
        tooShort
      },
      email: {
        valueMissing,
        typeMismatch: 'Digite um e-mail válido',
        tooShort
      },
      'select-one': {
        valueMissing
      },
      textarea: {
        valueMissing
      },
      password: {
        valueMissing
      },
      date: {
        valueMissing
      },
      month: {
        valueMissing
      },
      checkbox: {
        valueMissing
      }
    }
    return messages[field.type][errorType]
  }

  function setFieldRed (field) {
    field.classList.add('border-red-600')
    field.classList.add('placeholder-red-600')
  }

  function setFieldDefault (field) {
    field.classList.remove('border-red-600')
    field.classList.remove('placeholder-red-600')
  }

  function setValidationMessage (field) {
    const validationComponent = field.parentNode.querySelector('label.input-label--error')
    const hasError = fieldHasError(field)

    if (hasError) {
      const message = getCustomMessage(field, hasError)
      setFieldRed(field)
      if (validationComponent) validationComponent.innerHTML = message
    } else {
      setFieldDefault(field)
      if (validationComponent) validationComponent.innerHTML = ''
    }
  }

  function handleInvalidField (event) {
    const field = event.target
    setValidationMessage(field)
  }

  function validateForms () {
    const forms = document.querySelectorAll('form')

    if (!forms) return false

    forms.forEach(form => {
      const fields = form.querySelectorAll('[name]')

      for (const field of fields) {
        field.addEventListener('invalid', (event) => {
          event.preventDefault()
          handleInvalidField(event)
        })
        field.addEventListener('blur', handleInvalidField)
      }
    })
  }

  function start () {
    validateForms()
  }

  return {
    start
  }
}

export { FormValidation }
;;;