import { useI18n } from 'domains/i18n/hooks'
import { RootState } from 'domains/store'
import { useTranslatedEventData } from 'domains/translations/hooks'
import { className } from 'lib/css'
import { useMemo } from 'preact/hooks'
import { useSelector } from 'react-redux'
import MessageContainer from 'ui/components/conversation/message-container'
import Icon from 'ui/components/layout/icon'
import { useSeamlyApiContext } from 'ui/hooks/seamly-api-hooks'

const PROCESSING_IMAGE = 'PROCESSING_IMAGE'

const useImageFromStorage = (currentFileId) => {
  const { processingFileUploads } = useSelector(({ state }: RootState) => state)

  return useMemo(() => {
    const isProcessingImg = processingFileUploads.some(
      (fileId) => fileId === currentFileId,
    )

    if (isProcessingImg) return PROCESSING_IMAGE

    try {
      return sessionStorage.getItem(`image-${currentFileId}`)
    } catch (_error) {
      return undefined
    }
  }, [currentFileId, processingFileUploads])
}

const UploadedImage = ({ img, filename }) => {
  const { t } = useI18n()
  const srText = t('fileUpload.srFileUploadedText', { fileName: filename })

  return (
    <>
      <span className={className(['download', 'download--preview'])}>
        <img src={img} alt={srText} />
        <span aria-hidden="true" className={className('file-download')}>
          {filename}
        </span>
      </span>
    </>
  )
}

const UploadContent = ({
  children,
  fileId,
  isDeleted,
  onClickHandler,
  url,
  target,
}) => {
  if (fileId && !isDeleted) {
    return (
      <button
        type="button"
        onClick={onClickHandler}
        className={className(['download', 'download-link'])}
      >
        {children}
      </button>
    )
  }

  if (url) {
    return (
      <a
        href={url}
        download
        target={target}
        className={className(['download', 'download-link'])}
      >
        {children}
      </a>
    )
  }

  return <span className={className('download')}>{children}</span>
}

const Upload = ({ event, ...props }) => {
  const { t } = useI18n()
  const { body } = useTranslatedEventData(event)
  const { fromClient, id } = event.payload
  const { filename, id: fileId, isDeleted, url } = body
  const api = useSeamlyApiContext()
  const img = useImageFromStorage(id)

  const downloadFileFromApi = () => {
    if (fileId && filename) {
      api.downloadFile(fileId, filename)
    }
  }

  const srText = useMemo(
    () =>
      !isDeleted && (url || fileId)
        ? t('fileUpload.srFileDownloadText', { fileName: filename })
        : t('fileUpload.srFileUploadedText', { fileName: filename }),
    [url, fileId, filename, isDeleted, t],
  )

  return (
    <MessageContainer event={event} type="upload" {...props}>
      {img && img !== PROCESSING_IMAGE ? (
        <UploadedImage img={img} filename={filename} />
      ) : (
        <UploadContent
          fileId={fileId}
          isDeleted={isDeleted}
          onClickHandler={downloadFileFromApi}
          url={url}
          target={!fromClient ? '_blank' : undefined}
        >
          <Icon name="download" size="16" alt={srText} />
          <span aria-hidden="true" className={className('file-download')}>
            {filename}
          </span>
        </UploadContent>
      )}
    </MessageContainer>
  )
}

export default Upload
