<template>
  <form @submit.prevent="onSubmit">
    <slot />
  </form>
</template>

<script lang="ts">
import { name } from './_components/KaFormField.vue'

type KaFormFieldElement = {
  hasBeenBlurred: boolean
  hasError: boolean
} & Vue

export default {
  computed: {
    inputFieldsWithError(): KaFormFieldElement[] {
      return this.findInputFieldsWithError(this)
    },
    inputFields(): KaFormFieldElement[] {
      return this.findInputFields(this)
    },
  },
  methods: {
    findInputFieldsWithError(
      element: KaFormFieldElement,
    ): KaFormFieldElement[] {
      if (
        element.$options.name === name &&
        (element as KaFormFieldElement).hasError
      ) {
        return [element]
      }
      return element.$children.reduce(
        (total, e) => [
          ...total,
          ...this.findInputFieldsWithError(e as KaFormFieldElement),
        ],
        [] as KaFormFieldElement[],
      )
    },
    findInputFields(element: KaFormFieldElement): KaFormFieldElement[] {
      if (element.$options.name === name) {
        return [element]
      }
      return element.$children.reduce(
        (total, e) => [
          ...total,
          ...this.findInputFields(e as KaFormFieldElement),
        ],
        [] as KaFormFieldElement[],
      )
    },
    onSubmit(): void {
      if (this.inputFieldsWithError.length) {
        this.inputFieldsWithError.forEach((i) => {
          i.hasBeenBlurred = true
        })
        this.inputFieldsWithError[0].$el.scrollIntoView({
          behavior: 'smooth',
          block: 'center',
        })
      } else {
        this.$emit('submit')
      }
    },
    clearBlurred(): void {
      this.inputFields.forEach((i) => {
        i.hasBeenBlurred = false
      })
    },
  },
}
</script>
