import { useI18n } from 'domains/i18n/hooks'
import { className } from 'lib/css'
import { useEffect, useRef, useState } from 'preact/hooks'
import Icon from 'ui/components/layout/icon'
import InOutTransition, {
  transitionStartStates,
} from 'ui/components/widgets/in-out-transition'
import { useSeamlyEntry } from 'ui/hooks/seamly-entry-hooks'
import {
  useFileUploadMeta,
  useLiveRegion,
  useSeamlyCurrentAgent,
  useSkiplinkTargetFocusing,
} from 'ui/hooks/seamly-hooks'
import { runIfElementContainsOrHasFocus } from 'ui/utils/general-utils'
import { entryTypes } from 'ui/utils/seamly-utils'

const UploadToggle = () => {
  const { t } = useI18n()
  const { showFileUpload, serviceAllowsUploads } = useFileUploadMeta()
  const [showUploadButton, setShowUploadButton] = useState(
    serviceAllowsUploads || false,
  )
  const focusSkiplinkTarget = useSkiplinkTargetFocusing()
  const prevServiceAllowsUploads = useRef<boolean | undefined | null>(null)
  const { setUserEntryType, activeEntry } = useSeamlyEntry()
  const uploadButton = useRef(null)
  const { sendPolite } = useLiveRegion()
  const hasAgent = !!useSeamlyCurrentAgent()

  useEffect(() => {
    const focusFn = () => {
      if (!serviceAllowsUploads) {
        focusSkiplinkTarget()
      }
    }
    runIfElementContainsOrHasFocus(uploadButton.current, focusFn)
    setShowUploadButton(serviceAllowsUploads || false)
  }, [serviceAllowsUploads, focusSkiplinkTarget])

  useEffect(() => {
    if (prevServiceAllowsUploads.current && !serviceAllowsUploads) {
      sendPolite(t('fileUpload.srUnavailableText'))
    }

    if (prevServiceAllowsUploads.current === false && serviceAllowsUploads) {
      sendPolite(t('fileUpload.srAvailableText'))
    }

    // We wait for the first agent to join before activating this check.
    // This is to avoid messages being sent to the screen reader on app
    // startup or app refresh.
    if (hasAgent) {
      prevServiceAllowsUploads.current = serviceAllowsUploads
    }
  }, [serviceAllowsUploads, hasAgent, sendPolite, t])

  const onClickHandler = () => {
    setUserEntryType(entryTypes.upload)
    focusSkiplinkTarget()
  }

  return !showFileUpload && activeEntry !== entryTypes.upload ? (
    <InOutTransition
      isActive={showUploadButton}
      transitionStartState={transitionStartStates.rendered}
    >
      <div className={className('upload-toggle-wrapper')}>
        <InOutTransition
          isActive={showUploadButton}
          transitionStartState={transitionStartStates.visuallyHidden}
        >
          <button
            className={className([
              'button',
              'button--secondary',
              'upload-toggle',
            ])}
            ref={uploadButton}
            aria-disabled={!showUploadButton}
            type="button"
            onClick={showUploadButton ? onClickHandler : undefined}
            tabIndex={!showUploadButton ? -1 : undefined}
          >
            <Icon
              name="file"
              size="32"
              alt={t('fileUpload.toggleButtonText')}
            />
          </button>
        </InOutTransition>
      </div>
    </InOutTransition>
  ) : null
}

export default UploadToggle
