import { useCallback, useMemo } from 'react'

import trim from 'lodash/trim'
import find from 'lodash/find'

import type { Languages } from 'config/languages'
import { formIds } from 'config/form'

import { useForm } from 'features/FormStore'

import { useUserInfoForm } from './useUserInfoForm'
import { useValidateForm } from './useValidateForm'
import { Lang, langOptions } from '../config'
import type { SaveWithLang } from '../../PagePersonalInfo/hooks'

export type Props = {
  loader?: boolean,
  onSubmit: (data: SaveWithLang) => void,
}

export const useUserInfo = ({ loader, onSubmit }: Props) => {
  const {
    hasChanges,
    readFormError,
    readFormValue,
    updateFormValue,
  } = useForm()
  const validateForm = useValidateForm()
  const { onPhoneBlur } = useUserInfoForm()
  const readTrimmedValue = useCallback(
    (fieldName: string) => trim(readFormValue(fieldName)) || null,
    [readFormValue],
  )
  const readNumberValue = useCallback(
    (fieldName: string) => {
      const value = readTrimmedValue(fieldName)
      return value ? Number(value) : null
    },
    [readTrimmedValue],
  )
  const handleSubmit = useCallback(() => {
    if (validateForm()) {
      const firstname = readTrimmedValue(formIds.firstname)
      const lastname = readTrimmedValue(formIds.lastname)
      const language = readTrimmedValue(formIds.language)
      const phone = readTrimmedValue(formIds.phone)
      const postalCode = readNumberValue(formIds.postalCode)
      const region = readTrimmedValue(formIds.region)
      const address_line1 = readTrimmedValue(formIds.address1)
      const address_line2 = readTrimmedValue(formIds.address2)
      const city = readTrimmedValue(formIds.city)
      const cityId = readNumberValue(formIds.cityId)
      const countryId = readNumberValue(formIds.countryId)
      onSubmit({
        address_line1,
        address_line2,
        city: cityId ? null : city,
        cityId,
        countryId,
        firstname,
        language,
        lastname,
        phone,
        postalCode,
        region,
      })
    }
  }, [
    onSubmit,
    readTrimmedValue,
    readNumberValue,
    validateForm,
  ])

  const lang = readFormValue(formIds.language) as Languages

  const selectedlangOption = useMemo(
    () => find(langOptions, { id: lang })?.name || '',
    [lang],
  )

  const onLangSelect = (selectedLang: Lang | null) => {
    if (selectedLang) {
      updateFormValue(formIds.language)(selectedLang.id)
    }
  }

  return {
    handleSubmit,
    hasChanges,
    lang: selectedlangOption,
    loader,
    onLangSelect,
    onPhoneBlur,
    readFormError,
    readFormValue,
    updateFormValue,
  }
}
