import FormProvider from 'domains/forms/provider'
import { useI18n } from 'domains/i18n/hooks'
import { useCallback, useMemo, useState } from 'preact/hooks'
import OptionsFrame from 'ui/components/options/options-frame'
import {
  useGeneratedId,
  useOptionButton,
  useSeamlyCommands,
  useSeamlyOptions,
} from 'ui/hooks/seamly-hooks'
import { getValidator } from 'ui/utils/form-utils'
import { actionTypes } from 'ui/utils/seamly-utils'
import { isEmailString, isNotEmptyString } from 'ui/utils/validations'
import TranscriptForm from './transcript-form'

const formId = 'sendTranscript'
const controlName = 'email'

const Transcript = () => {
  const [errorClass, setErrorClass] = useState<string | undefined>(undefined)
  const { hideOption } = useSeamlyOptions()
  const { focusButton } = useOptionButton()
  const { t } = useI18n()
  const transcriptDescriptionId = useGeneratedId()
  const { sendAction } = useSeamlyCommands()

  const validationSchema = useMemo(
    () => ({
      [controlName]: [
        getValidator(isNotEmptyString, t('options.sendTranscript.noEmailText')),
        getValidator(
          isEmailString,
          t('options.sendTranscript.invalidEmailText'),
        ),
      ],
    }),
    [t],
  )

  const handleSubmit = useCallback(
    (values) => {
      const emailAddress = values[controlName].trim()
      sendAction({
        type: actionTypes.sendTranscript,
        body: { emailAddress },
      })
      hideOption()
      focusButton()
    },
    [sendAction, hideOption, focusButton],
  )

  const handleError = useCallback(
    ({ isValid, isSubmitted }) => {
      if (isSubmitted && !isValid) {
        setErrorClass('options--error')
      } else {
        setErrorClass(undefined)
      }
    },
    [setErrorClass],
  )

  return (
    <OptionsFrame
      className={errorClass}
      headingText={t('options.sendTranscript.title')}
      cancelButtonText={t('options.cancelButtonText')}
      description={t('options.sendTranscript.description')}
      descriptionId={transcriptDescriptionId}
      position={{
        vertical: 'top',
        horizontal: 'right',
      }}
    >
      <FormProvider
        formId={formId}
        onSubmit={handleSubmit}
        validationSchema={validationSchema}
        onError={handleError}
      >
        <TranscriptForm
          controlName={controlName}
          describedById={transcriptDescriptionId}
        />
      </FormProvider>
    </OptionsFrame>
  )
}

export default Transcript
