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

import CardActionArea from '@material-hu/mui/CardActionArea';

import { type Attachment, FileTypes } from 'src/types/attachments';
import { type File } from 'src/types/files';

import FilePreview from 'src/components/attachment/FilePreview';
import MediaBase from 'src/components/attachment/MediaBase';

import { type HeaderFile } from './preview/Header';

export type MediaProps = {
  media: Attachment;
  mediaList?: Attachment[];
  height?: number;
  width?: number;
  onDownload?: (file: HeaderFile) => void;
  grantVideoDownload?: boolean;
};

const Media: FC<MediaProps> = props => {
  const {
    media,
    mediaList = [media],
    height = undefined,
    width = undefined,
    onDownload = () => null,
    grantVideoDownload = false,
  } = props;

  const { type } = media;

  const [expandMedia, setExpandMedia] = useState<boolean>(false);

  const [index, setIndex] = useState(0);

  useEffect(() => {
    if (expandMedia) {
      setIndex(mediaList.findIndex(attachment => attachment.url === media.url));
    }
  }, [expandMedia, media.url]);

  const openExpandMedia = () => setExpandMedia(true);
  const closeExpandMedia = () => setExpandMedia(false);

  if (type === FileTypes.VIDEO) {
    return (
      <MediaBase
        media={media}
        mediaHeight={height}
        mediaWidth={width}
        grantVideoDownload={grantVideoDownload}
      />
    );
  }

  const handleGoBack = () => setIndex(index - 1);

  const handleGoForward = () => setIndex(index + 1);

  const isNavigationButtonGoBackDisabled = index === 0;

  const isNavigationButtonGoForwardDisabled = index === mediaList.length - 1;

  return (
    <>
      <CardActionArea
        onClick={openExpandMedia}
        sx={{
          height: height ? height : 'inherit',
          width: width ? width : 'auto',
          display: 'flex',
        }}
      >
        <MediaBase
          media={media}
          mediaHeight={height}
          mediaWidth={width}
        />
      </CardActionArea>
      <FilePreview
        open={expandMedia}
        isPost
        //TODO: fix type on FilePreview
        currentFile={mediaList[index] as Partial<File> & Partial<Attachment>}
        onGoBack={handleGoBack}
        onGoForward={handleGoForward}
        isNavigationButtonGoBackDisabled={isNavigationButtonGoBackDisabled}
        isNavigationButtonGoForwardDisabled={
          isNavigationButtonGoForwardDisabled
        }
        headerProps={{
          onDownload: onDownload,
          onClose: closeExpandMedia,
        }}
      />
    </>
  );
};

export default Media;
