import { FC, useState } from 'react';

import { FileAsset } from '@material-hu/types/attachments';

import HuLink from '@material-hu/components/design-system/Link';

import { FileTypes } from 'src/types/attachments';

import {
  getFileNameExtension,
  isPdf,
  isVideoFile,
  safeConvertFileAssetToAttachment,
} from 'src/utils/files';

import FullMediaCarousel from 'src/components/attachment/FullMediaCarousel';
import PdfViewer from 'src/components/attachment/PdfViewer';

export type FileAnswerProps = {
  file: FileAsset;
};

const FileAnswer: FC<FileAnswerProps> = props => {
  const { file } = props;
  const [expandedImg, setExpandedImg] = useState<FileAsset | null>(null);
  const [expandedVideo, setExpandedVideo] = useState<FileAsset | null>(null);
  const [expandedPdfFile, setExpandedPdfFile] = useState<FileAsset | null>(
    null,
  );

  const handleOpenFilePreview = () => {
    if (file.type === 'IMAGE') {
      setExpandedImg(file);
    } else if (isVideoFile(getFileNameExtension(file.name))) {
      setExpandedVideo(file);
    } else if (isPdf(getFileNameExtension(file.name))) {
      setExpandedPdfFile(file);
    } else {
      window.open(file.url, '_blank', 'noopener,noreferrer');
    }
  };

  return (
    <>
      <HuLink onClick={handleOpenFilePreview}>{file.name}</HuLink>
      {expandedPdfFile && (
        <PdfViewer
          file={safeConvertFileAssetToAttachment(expandedPdfFile)}
          onClose={() => setExpandedPdfFile(null)}
        />
      )}
      {expandedImg && (
        <FullMediaCarousel
          open={!!expandedImg}
          mediaList={[safeConvertFileAssetToAttachment(expandedImg)]}
          showName
          showDownload
          onClose={() => setExpandedImg(null)}
        />
      )}
      {expandedVideo && (
        <FullMediaCarousel
          open={!!expandedVideo}
          mediaList={[
            {
              ...safeConvertFileAssetToAttachment(expandedVideo),
              type: FileTypes.VIDEO,
            },
          ]}
          showName
          showDownload
          onClose={() => setExpandedVideo(null)}
        />
      )}
    </>
  );
};

export default FileAnswer;
