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

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

interface AvatarProps {
  showAvatar: boolean
}

export const ChatMessageWithAvatar: React.FC<ChatMessageProps & AvatarProps> = ({
  chatMessage,
  getAttachmentLocation,
  showAvatar,
  components,
  styles,
}) => {
  const { id: localParticipantId } = useZocksStore(selectLocalParticipant)
  const {
    from: { id: senderId, name: senderName },
    message,
    attachment,
  } = chatMessage

  const sentByMe = senderId === localParticipantId

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

  return (
    <div
      className={classNames(getClassName('chat-message-a__container', mergedStyles), {
        [getClassName('chat-message-a__container--sent', mergedStyles)]: sentByMe,
        [getClassName('chat-message-a__container--received', mergedStyles)]: !sentByMe,
      })}
    >
      {showAvatar && (
        <div className={getClassName('chat-message-a__avatar', mergedStyles)} title={senderName}>
          {senderName.slice(0, 1)}
        </div>
      )}
      <div
        className={classNames(getClassName('chat-message-a__message-container', mergedStyles), {
          [getClassName('chat-message-a--indent-sent', mergedStyles)]: !showAvatar && sentByMe,
          [getClassName('chat-message-a--indent-received', mergedStyles)]: !showAvatar && !sentByMe,
        })}
      >
        {message && (
          <Linkify options={linkifyOptions}>
            <div className={getClassName('chat-message-a__message', mergedStyles)}>{message}</div>
          </Linkify>
        )}
        {attachment && getAttachmentLocation && (
          <ChatMessageAttachmentElement
            attachment={attachment}
            getAttachmentLocation={getAttachmentLocation}
            styles={mergedStyles}
          />
        )}
      </div>
    </div>
  )
}
