import { useConfig } from 'domains/config/hooks'
import { useI18n } from 'domains/i18n/hooks'
import { className } from 'lib/css'
import { useRef } from 'preact/hooks'
import Icon from 'ui/components/layout/icon'
import {
  useSeamlyActivityEventHandler,
  useSeamlyAppContainerClassNames,
} from 'ui/hooks/seamly-hooks'
import Modal from './modal'

const Lightbox = ({ url, description, onClose: onCloseHandler }) => {
  const config = useConfig()
  const onActivityHandler = useSeamlyActivityEventHandler()
  const appContainerClassNames = useSeamlyAppContainerClassNames()
  const focusContainer = useRef<HTMLDivElement>(null)
  const { t } = useI18n()

  // TODO: Change incorrect usage of css modifiers
  const defaultClassNames = [
    `app--layout-${config.layoutMode}`,
    `namespace--${config.namespace}`,
  ]
  const classNames = ['modal', ...defaultClassNames]

  if (typeof appContainerClassNames !== 'function') {
    classNames.push(...appContainerClassNames)
  } else {
    classNames.push(...appContainerClassNames(config))
  }

  const onFrameClickHandler = (e) => {
    e.stopPropagation()
  }

  const onFloatClickHandler = () => {
    onCloseHandler()
  }

  const style = config?.zIndex ? { zIndex: config.zIndex + 1 } : undefined

  const getModalContent = (onClose) => (
    <div
      className={className(classNames)}
      onClick={onFloatClickHandler}
      style={style}
    >
      <div
        className={className('modal__float')}
        tabIndex={-1}
        onMouseDown={onActivityHandler}
        onKeyDown={onActivityHandler}
        onTouchStart={onActivityHandler}
        onMouseMove={onActivityHandler}
        onWheel={onActivityHandler}
        onPointerDown={onActivityHandler}
        onPointerMove={onActivityHandler}
        ref={focusContainer}
      >
        <div
          className={className('modal__inner')}
          onClick={onFrameClickHandler}
        >
          <img
            className={className('modal__image')}
            src={url}
            alt={description}
          />
        </div>
        <button
          type="button"
          className={className('modal__close')}
          onClick={onClose}
        >
          <Icon name="close" size="16" alt="" />
          {t('lightbox.closeLabel')}
        </button>
      </div>
    </div>
  )

  return (
    <Modal
      onClose={onCloseHandler}
      aria-label={t('lightbox.heading')}
      fallBackFocusRef={focusContainer}
    >
      {({ onClose, modalRenderFn }) => modalRenderFn(getModalContent(onClose))}
    </Modal>
  )
}

export default Lightbox
