import React from 'react'
import classNames from 'classnames'
import Linkify from 'linkify-react'
import { useZocksStore } from '../../../app'
import { selectLocalParticipant } from '../../../store'
import { getClassName, getMergedClassNames } from '../../common'
import { ChatMessageProps } from '../models'
import { ChatMessageAttachment } from './ChatMessageAttachment'
import zocksStyle from './ChatMessageWithParticipantInfo.module.scss'

const linkifyOptions = {
  defaultProtocol: 'https',
  target: '_blank',
}

interface InfoProps {
  showParticipantInfo: boolean
  localParticipantLabel?: string
}

export const ChatMessageWithParticipantInfo: React.FC<ChatMessageProps & InfoProps> = ({
  chatMessage,
  getAttachmentLocation,
  showParticipantInfo,
  localParticipantLabel = 'Me',
  components,
  styles,
}) => {
  const { id: localParticipantId } = useZocksStore(selectLocalParticipant)
  const {
    from: { id: senderId, name: senderName },
    to: { id: recipientId, name: recipientName } = {},
    message,
    attachment,
  } = chatMessage

  const sentByMe = senderId === localParticipantId
  const forMe = recipientId === localParticipantId
  const directMessage = !!recipientId

  const headerText =
    `${sentByMe ? localParticipantLabel : senderName}` +
    (directMessage ? ` To ${forMe ? localParticipantLabel : recipientName}` : '')

  const ChatMessageAttachmentElement = components?.ChatMessageAttachment ?? ChatMessageAttachment
  const mergedStyles = getMergedClassNames(zocksStyle, styles)

  return (
    <div
      className={classNames(getClassName('chat-message-i__container', mergedStyles), {
        [getClassName('chat-message-i__container--sent', mergedStyles)]: sentByMe,
        [getClassName('chat-message-i__container--received', mergedStyles)]: !sentByMe,
      })}
    >
      {showParticipantInfo && (
        <div className={getClassName('chat-message-i__header-container')}>
          <div className={getClassName('chat-message-i__avatar', mergedStyles)} title={senderName}>
            {senderName.slice(0, 1)}
          </div>
          <div
            className={classNames(getClassName('chat-message-i__header', mergedStyles), {
              [getClassName('chat-message-i__header--public', mergedStyles)]: !directMessage,
              [getClassName('chat-message-i__header--private', mergedStyles)]: directMessage,
            })}
          >
            {headerText}
          </div>
        </div>
      )}
      {message && (
        <Linkify options={linkifyOptions}>
          <div className={getClassName('chat-message-i__message', mergedStyles)}>{message}</div>
        </Linkify>
      )}
      {attachment && getAttachmentLocation && (
        <ChatMessageAttachmentElement
          attachment={attachment}
          getAttachmentLocation={getAttachmentLocation}
          styles={mergedStyles}
        />
      )}
    </div>
  )
}
