import {
  InfoEvent,
  MessageEvent,
  ServiceDataEvent,
} from 'domains/store/store.types'
import { useTranslatedEventData } from 'domains/translations/hooks'
import { className } from 'lib/css'
import { PreactDOMAttributes } from 'preact'
import { FC, HTMLAttributes } from 'preact/compat'
import { useSeamlyMessageContainerClassNames } from 'ui/hooks/component-helper-hooks'
import EventParticipant from './event/event-participant'

export type MessageContainerProps = {
  showParticipant?: boolean
  event: MessageEvent | InfoEvent | ServiceDataEvent
  type?: string
  modifiers?: string | string[]
  bodyProps?: HTMLAttributes<HTMLDivElement> & PreactDOMAttributes
  info?: string
  onClick?: (_event: MouseEvent) => void
}

const MessageContainer: FC<MessageContainerProps> = ({
  showParticipant = true,
  event,
  type,
  modifiers,
  children,
  bodyProps = {},
  info,
  ...props
}) => {
  const classNames = useSeamlyMessageContainerClassNames(event)

  const { hasTranslation, isTranslated, locale } = useTranslatedEventData(event)

  if (type) {
    classNames.push(`message--type-${type}`)
  }
  if (modifiers) {
    if (typeof modifiers === 'string') {
      modifiers = modifiers.split(' ').filter((v) => v.length)
    }
    modifiers.forEach((modifier) => {
      classNames.push(`message--${modifier}`)
    })
  }
  if (isTranslated) {
    classNames.push('message--is-translated')
  }
  if (hasTranslation) {
    classNames.push('message--has-translation')
  }

  if (isTranslated) {
    bodyProps = {
      ...bodyProps,
      lang: locale,
    }
  }

  return (
    <>
      <div className={className(classNames)} {...props}>
        {showParticipant && <EventParticipant eventPayload={event.payload} />}
        <div className={className('message__body')} {...bodyProps}>
          {children}
        </div>
        {info && (
          <div aria-hidden="true" className={className('message__info')}>
            {info}
          </div>
        )}
      </div>
    </>
  )
}

export default MessageContainer
