import { useForm } from 'react-hook-form'
import { Prompt, useHistory } from 'react-router-dom'
import {
  Semantic,
  ToastProps,
  TollFreeRegistrationForm,
  TollFreeRegistrationPage,
  useModal
} from '@komi-app/creator-ui'
import { dcaSettingsUrl } from 'constants/dca'
import {
  countriesOptions,
  countryCodeOptions,
  emailRegExp,
  formDefaultValues,
  phoneRegExp,
  SMSVolumeOptions,
  websiteRegExp
} from './TollFreeRegisterConfig'
import { ToastContainer } from '../Toasts/ToastContainer'
import { useState } from 'react'
import { getSMSService } from 'services'

const TollFreeRegister: React.FC = () => {
  const [toastConfig, setToastConfig] = useState<ToastProps | null>(null)
  const history = useHistory()
  const [isNavigationBlocked, setIsNavigationBlocked] = useState<boolean>(true)
  const { handleSubmit, control } = useForm<TollFreeRegistrationForm>({
    defaultValues: formDefaultValues
  })
  const {
    Modal: ConfirmationModal,
    openModal: showConfirmationModal,
    closeModal
  } = useModal()

  const onSubmit = async (data: TollFreeRegistrationForm) => {
    try {
      const { countryCode, number } = data.phoneNumber
      const completePhoneNumber = countryCode + number
      const request = { ...data, phoneNumber: completePhoneNumber }
      await getSMSService().submitTollFreeNumberVerification(request)

      await setIsNavigationBlocked(false)
      history.push(dcaSettingsUrl, { hasRegisteredTollFree: true })
    } catch (error) {
      setToastConfig({
        text: 'We couldn’t save your business details. Try again.',
        semantic: 'error',
        showIcon: true,
        dismissible: true
      })
    }
  }

  const onLeaveRegistration = async () => {
    await setIsNavigationBlocked(false)
    closeModal()
    /**
     * If user leaves the page without registering,
     * show them toast for phone number procurement.
     */
    history.push(dcaSettingsUrl, { hasProcuredNumber: true })
  }

  return (
    <>
      <TollFreeRegistrationPage
        previousPageURL={dcaSettingsUrl}
        countryCodeOptions={countryCodeOptions}
        volumeOptions={SMSVolumeOptions}
        countriesOptions={countriesOptions}
        emailRegExp={emailRegExp}
        phoneRegExp={phoneRegExp}
        websiteRegExp={websiteRegExp}
        control={control}
        handleSubmit={handleSubmit}
        onSaveClick={onSubmit}
        onCancelClick={showConfirmationModal}
      />
      <ConfirmationModal
        heading="Cancel registration?"
        body={`Your phone number will be reserved, but you won’t be able to send SMS until you register.`}
        buttons={[
          {
            label: 'Dismiss',
            semantic: Semantic.SECONDARY,
            onClick: onLeaveRegistration
          },
          {
            label: 'Continue',
            semantic: Semantic.PRIMARY,
            onClick: closeModal
          }
        ]}
        dismissible={false}
      />
      {toastConfig && (
        <ToastContainer {...toastConfig} setProps={setToastConfig} />
      )}
      <Prompt
        when={isNavigationBlocked}
        message={() => {
          showConfirmationModal()
          return false
        }}
      />
    </>
  )
}

export default TollFreeRegister
