import { MessageText } from 'domains/store/store.types'
import { useTranslatedEventData } from 'domains/translations/hooks'
import { FunctionalComponent } from 'preact'
import { useMemo } from 'preact/hooks'
import MessageContainer, {
  MessageContainerProps,
} from 'ui/components/conversation/message-container'
import useEventLinkClickHandler from './hooks/use-event-link-click-handler'

type TextProps = {
  event: Partial<MessageText>
} & Partial<MessageContainerProps>

const Text: FunctionalComponent<TextProps> = ({ event, ...props }) => {
  const { body } = useTranslatedEventData(event)

  const eventClick = useEventLinkClickHandler({
    originMessage: event.payload.id,
    transactionId: event.payload.transactionId,
  })

  const containerProps = useMemo(() => {
    if (event.payload.optimisticallyInjected) {
      return {
        children: <p>{body?.text}</p>,
      }
    }

    return {
      bodyProps: {
        dangerouslySetInnerHTML: {
          __html: body?.text || '',
        },
      },
    }
  }, [body, event])

  return (
    <MessageContainer
      type="text"
      event={event}
      onClick={eventClick}
      {...props}
      {...containerProps}
    />
  )
}

export default Text
