import { FC, useEffect, useState } from 'react';

import Box from '@material-hu/mui/Box';
import CircularProgress from '@material-hu/mui/CircularProgress';
import { SxProps } from '@material-hu/mui/styles';

import HuFileCard from '@material-hu/components/design-system/FileCard';

import { useIntersectionObserver } from 'src/hooks/useIntersectionObserver';
import { isVideoAttachment } from 'src/pages/dashboard/Conversations/utils';
import { bytesToSize } from 'src/utils/bytes';
import { urlToFile } from 'src/utils/files';

import { useGetCorrectAttachmentUrl } from '../../hooks/useConversationsQueries';

type LazySecureFileProps = {
  file: any;
  sx?: SxProps;
  isDownloadable?: boolean;
  conversationId?: string;
};

const LazySecureFile: FC<LazySecureFileProps> = props => {
  const { file, sx, isDownloadable = false, conversationId } = props;

  const [createdFile, setCreatedFile] = useState<File | undefined>(undefined);
  const url = isVideoAttachment(file) ? file.video_url : file.url;

  const { targetRef, hasBeenVisible } = useIntersectionObserver();

  const { data, isLoading } = useGetCorrectAttachmentUrl({
    url,
    conversationId,
    enabledToShowError: false,
    enabled: !!url && hasBeenVisible,
  });

  useEffect(() => {
    const createFileFromUrl = async () => {
      if (data && file.filename && isDownloadable) {
        const newFile = await urlToFile(data, file.filename);
        setCreatedFile(newFile);
      }
    };
    createFileFromUrl();
  }, [data, isDownloadable, file.filename]);

  if (isLoading || !data || !hasBeenVisible) {
    return (
      <Box
        ref={targetRef}
        sx={{
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          minHeight: 76,
          width: 330,
          ...sx,
        }}
      >
        <CircularProgress size={24} />
      </Box>
    );
  }

  return (
    <div ref={targetRef}>
      <HuFileCard
        status="default"
        file={createdFile}
        attachment={{
          url: data,
          name: file.filename,
          type: file.mimetype,
          size: bytesToSize(file.size),
          bytes: file.size,
        }}
        sx={sx}
      />
    </div>
  );
};

export default LazySecureFile;
