import { useInterrupt } from 'domains/interrupt/hooks'
import { className } from 'lib/css'
import { useEffect } from 'preact/hooks'
import CollapseButton from 'ui/components/view/window-view/collapse-button'
import {
  useGeneratedId,
  useLiveRegion,
  useSeamlyCommands,
  useSkiplinkTargetFocusing,
} from 'ui/hooks/seamly-hooks'

const Interrupt = () => {
  const {
    meta: { originalError, title, message, buttonText, action, srText },
  } = useInterrupt()
  const seamlyCommands = useSeamlyCommands()
  const headingId = useGeneratedId()
  const { sendPolite } = useLiveRegion()
  const focusSkiplinkTarget = useSkiplinkTargetFocusing()
  const isExpiredError = originalError?.name === 'SeamlySessionExpiredError'

  useEffect(() => {
    if (!isExpiredError && srText) {
      // Wait for live regions to stabilise in case this occurs
      // at an initial render
      setTimeout(() => {
        sendPolite(srText)
      }, 200)
    }
  }, [sendPolite, srText, isExpiredError])

  const onClickHandler = () => {
    if (action && seamlyCommands[action]) {
      seamlyCommands[action]()
    }
    focusSkiplinkTarget()
  }

  return !isExpiredError ? (
    <section className={className('interrupt')} aria-labelledby={headingId}>
      <CollapseButton />
      <div className={className('interrupt__body')}>
        <h2 id={headingId} className={className('interrupt__title')}>
          {title}
        </h2>
        <p className={className('interrupt__message')}>{message}</p>
        {buttonText && action && (
          <div className={className('interrupt__actions')}>
            <button
              type="button"
              className={className('button', 'button--primary')}
              onClick={onClickHandler}
            >
              {buttonText}
            </button>
          </div>
        )}
      </div>
    </section>
  ) : (
    <></>
  )
}

export default Interrupt
