import React from 'react'
import { ChatMessageAttachmentProps } from '../models'
import { useChatAttachment } from '../hooks'
import { getClassName, getMergedClassNames } from '../../common'
import zocksStyle from './ChatMessageAttachment.module.scss'

export const ChatMessageAttachment: React.FC<ChatMessageAttachmentProps> = ({
  attachment,
  getAttachmentLocation,
  styles,
}) => {
  const { anchorRef, isAttachmentLoading, hasAttachmentError, attachmentUrl, downloadAttachment } = useChatAttachment(
    attachment,
    getAttachmentLocation
  )
  const mergedStyles = getMergedClassNames(zocksStyle, styles)
  return (
    <div className={getClassName('chat-message-attachment__container', mergedStyles)}>
      <div className={getClassName('chat-message-attachment__name', mergedStyles)}>{attachment.fileName}</div>
      <button
        className={getClassName('chat-message-attachment__download-button', mergedStyles)}
        disabled={isAttachmentLoading}
        onClick={downloadAttachment}
      >
        Download
      </button>
      <a
        ref={anchorRef}
        className={getClassName('chat-message-attachment__hidden-link', mergedStyles)}
        href={attachmentUrl}
        download={attachment.fileName}
        target='_blank'
        rel='noreferrer noopener'
      >
        {' '}
      </a>
      {hasAttachmentError && <div>Error while downloading the attachment.</div>}
    </div>
  )
}
