import { useI18n } from 'domains/i18n/hooks'
import { className } from 'lib/css'
import { useSkiplinkTargetFocusing } from 'ui/hooks/focus-helper-hooks'
import useSeamlyActivityEventHandler from 'ui/hooks/use-seamly-activity-event-handler'
import useSeamlyCommands from 'ui/hooks/use-seamly-commands'
import useSeamlyIdleDetachCountdown from 'ui/hooks/use-seamly-idle-detach-countdown'
import Prompt from './prompt'

const IdleDetachWarning = () => {
  const { t } = useI18n()
  const focusSkiplinkTarget = useSkiplinkTargetFocusing()
  const sendActivity = useSeamlyActivityEventHandler()
  const { emitEvent } = useSeamlyCommands()

  const { isActive, remaining, timer, endCountdown } =
    useSeamlyIdleDetachCountdown()

  const continueChat = () => {
    sendActivity()
    endCountdown(true)
    focusSkiplinkTarget()
    emitEvent('idleTimer.selectContinue')
  }

  const transferChat = () => {
    endCountdown()
    focusSkiplinkTarget()
    emitEvent('idleTimer.selectEnd')
  }

  const countDownComplete = remaining ? remaining > 0 : false
  const title = countDownComplete
    ? t('idleDetachWarning.countdownTitle')
    : t('idleDetachWarning.notifyTransferText')

  return (
    <Prompt baseClassName="idle" title={title}>
      {countDownComplete && (
        <>
          <div className={className('idle__count-container')}>
            {isActive && (
              <>
                <span className={className('idle__count-text')}>
                  {t('idleDetachWarning.countdownText')}
                </span>
                <span className={className('idle__count-timer')}>
                  {t('idleDetachWarning.countdownTimer', timer)}
                </span>
              </>
            )}
          </div>
          <div className={className('idle__options')}>
            <button
              type="button"
              className={className('button', 'button--primary')}
              onClick={continueChat}
            >
              {t('idleDetachWarning.continueButton')}
            </button>
            <button
              type="button"
              className={className('button', 'button--primary')}
              onClick={transferChat}
            >
              {t('idleDetachWarning.detachButton')}
            </button>
          </div>
        </>
      )}
    </Prompt>
  )
}

export default IdleDetachWarning
