import { type FC } from 'react';

import { IconFile } from '@material-hu/icons/tabler';
import Box from '@material-hu/mui/Box';
import { type SxProps } from '@material-hu/mui/styles';

import HuAvatar from '@material-hu/components/design-system/Avatar';

import { BUNNY_IMAGE_CLASSES } from 'src/pages/dashboard/Conversations/constants';
import { type SendFileItem } from 'src/pages/dashboard/Conversations/types';
import {
  isFileAttachment,
  isGifAttachment,
  isImageAttachment,
  isVideoAttachment,
} from 'src/pages/dashboard/Conversations/utils';

import Gif, { type MediaBaseProps } from 'src/components/attachment/Gif';

import LazySecureAwareImage from './LazySecureAwareImage';
import LazySecureAwareVideo from './LazySecureAwareVideo';

type AttachmentThumbnailProps = {
  attachment: SendFileItem;
  width?: number;
  height?: number;
};

const sxMedia: SxProps = {
  objectFit: 'cover',
  width: '100%',
  height: '100%',
  position: 'relative',
  '& video': { objectFit: 'cover', height: '100%', width: '100%' },
};

const AttachmentThumbnail: FC<AttachmentThumbnailProps> = ({
  attachment,
  width = 40,
  height = 40,
}) => {
  if (isImageAttachment(attachment)) {
    return (
      <Box
        sx={{
          width,
          height,
          flexShrink: 0,
          borderRadius: 1,
          overflow: 'hidden',
        }}
      >
        <LazySecureAwareImage
          isSecure={false}
          url={attachment.image_url}
          alt={attachment.filename}
          sxSecure={sxMedia}
          sxDefault={sxMedia}
          imageClass={BUNNY_IMAGE_CLASSES.FA_THUMB}
        />
      </Box>
    );
  }

  if (isVideoAttachment(attachment)) {
    return (
      <Box
        sx={{
          width,
          height,
          flexShrink: 0,
          borderRadius: 1,
          overflow: 'hidden',
        }}
      >
        <LazySecureAwareVideo
          isSecure={false}
          avatarSize="small"
          url={attachment.video_url}
          thumbUrl={attachment.thumb_url}
          sxSecure={sxMedia}
          sxDefault={sxMedia}
        />
      </Box>
    );
  }

  if (isGifAttachment(attachment)) {
    return (
      <Gif
        media={attachment as MediaBaseProps['media']}
        width={Math.min(width, height)}
        withLimitDuration
        duration={0}
      />
    );
  }

  if (isFileAttachment(attachment)) {
    return (
      <HuAvatar
        color="primary"
        sx={{ mx: 1 }}
        Icon={IconFile}
      />
    );
  }

  return null;
};

export default AttachmentThumbnail;
