import type { FormEvent } from 'react'

import trim from 'lodash/trim'

import type { City } from 'requests'

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

import { formIds } from '../config'
import type { Country } from './useCountries'
import { useValidateForm } from './useValidateForm'

type Args = {
  selectedCity: City | null,
  selectedCountry: Country | null,
}

export const useSubmitHandler = ({
  selectedCity,
  selectedCountry,
}: Args) => {
  const { register } = useAuthStore()
  const { readFormValue } = useForm()
  const validateForm = useValidateForm()

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

  const getCityParams = () => {
    if (selectedCity) return { cityId: selectedCity.id }
    return { city: readTrimmedValue(formIds.city) }
  }

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

    if (validateForm() && selectedCountry) {
      const firstname = readTrimmedValue(formIds.firstname)
      const lastname = readTrimmedValue(formIds.lastname)
      const phone = readTrimmedValue(formIds.phone)
      const email = readTrimmedValue(formIds.email)
      const password = readTrimmedValue(formIds.password)
      const postalCode = Number(readTrimmedValue(formIds.postalCode))
      const region = readTrimmedValue(formIds.region)
      const address1 = readTrimmedValue(formIds.address1)
      const address2 = readTrimmedValue(formIds.address2)

      register({
        address1,
        address2,
        ...getCityParams(),
        countryId: selectedCountry.id,
        email,
        firstname,
        lastname,
        password,
        phone,
        postalCode,
        region,
      })
    }
  }

  return handleSubmit
}
