import { type FC, useEffect, useRef } from 'react';
import Carousel from 'react-material-ui-carousel';

import { Stack, useTheme } from '@mui/material';

import { type CompleteFile } from '../../../types/attachments';
import { FileTypes } from '../../../utils/files';

type MediaCarrouselProps = {
  media?: CompleteFile[];
  pauseVideosOnChange?: boolean;
};
export const MediaCarrousel: FC<MediaCarrouselProps> = ({
  media,
  pauseVideosOnChange = true,
}) => {
  const { palette } = useTheme();
  const videoRefs = useRef<(HTMLVideoElement | null)[]>([]);

  if (!media?.length) return null;

  useEffect(() => {
    videoRefs.current = videoRefs.current.slice(0, media.length);
  }, [media]);

  const pauseVideos = () => {
    videoRefs.current.forEach(videoRef => {
      if (videoRef) {
        videoRef.pause();
      }
    });
  };

  const onHandleChange = () => {
    if (pauseVideosOnChange) {
      pauseVideos();
    }
  };

  return (
    <Carousel
      indicators={media.length > 1}
      onChange={onHandleChange}
      navButtonsAlwaysVisible
      navButtonsAlwaysInvisible={media.length === 1}
      fullHeightHover={false}
      cycleNavigation={false}
      height={400}
      autoPlay={false}
      indicatorIconButtonProps={{
        style: {
          color: palette.new.background.layout.brand,
        },
      }}
      activeIndicatorIconButtonProps={{
        style: {
          color: palette.base?.blueBrand[400],
        },
      }}
    >
      {media.map((item, index) => {
        let content = null;
        switch (item.attachment!.type) {
          case FileTypes.IMAGE:
            content = (
              <Stack
                component="img"
                key={item.id}
                src={item.attachment!.url}
                alt={item.attachment!.name}
                sx={{
                  height: '100%',
                  mx: 'auto',
                }}
              />
            );
            break;
          case FileTypes.VIDEO:
            content = (
              <Stack
                ref={el => {
                  videoRefs.current[index] = el;
                }}
                component="video"
                key={item.id}
                src={item.attachment!.url}
                sx={{
                  height: '100%',
                  mx: 'auto',
                  cursor: 'pointer',
                }}
                controls
              />
            );
            break;
          default:
            content = null;
            break;
        }
        return content;
      })}
    </Carousel>
  );
};

export default MediaCarrousel;
