import type { FormEvent } from 'react'

import trim from 'lodash/trim'

import { formIds } from 'config/form'

import { useAuthStore } from 'features/AuthStore'
import { useForm } from 'features/FormStore'

import { useValidateForm } from './useValidateForm'

export const useSubmitHandler = () => {
  const { register } = useAuthStore()
  const { readFormValue } = useForm()
  const validateForm = useValidateForm()

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

  const handleSubmit = async (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault()

    if (validateForm()) {
      const firstname = readTrimmedValue(formIds.firstname)
      const lastname = readTrimmedValue(formIds.lastname)
      const email = readTrimmedValue(formIds.email)
      const password = readTrimmedValue(formIds.password)

      register({
        email,
        firstname,
        lastname,
        password,
      })
    }
  }

  return handleSubmit
}
