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

import { type SxProps, useTheme } from '@material-hu/mui';

import HuSkeleton from '@material-hu/components/design-system/Skeleton';

import useHuGoTheme from 'src/hooks/useHuGoTheme';
import { type Attachment } from 'src/types/attachments';
import { getMediaHeight } from 'src/utils/attachments';

import Media from 'src/components/attachment/Media';

export type MediaCarouselProps = {
  mediaList: Attachment[];
  className?: string;
  isPost?: boolean;
  parentContainerId?: string;
  sx?: SxProps;
  onDownload?: (file: Attachment) => void;
  width?: string | number;
  grantVideoDownload?: boolean;
  mediaMaxHeight?: number;
};

export const MediaCarousel: FC<MediaCarouselProps> = props => {
  const {
    mediaList,
    className,
    isPost = false,
    sx = {},
    parentContainerId,
    onDownload = () => null,
    width: propWidth,
    grantVideoDownload,
    mediaMaxHeight,
  } = props;

  const [width, setWidth] = useState<number>(0);
  const [height, setHeight] = useState<number>(0);
  const [isReadyToRender, setIsReadyToRender] = useState(false);

  const theme = useTheme();
  const calculatedHeight = getMediaHeight(
    mediaList,
    parentContainerId,
    mediaMaxHeight,
  );

  // Effect to handle width updates from ResizeObserver
  useEffect(() => {
    if (!parentContainerId) return;
    const postCard = document.getElementById(parentContainerId);

    if (!postCard) return;

    setWidth(postCard.offsetWidth || 400);

    const resizeObserver = new ResizeObserver(entries => {
      for (const entry of entries) {
        const element = entry.target as HTMLElement;
        const newWidth = element.offsetWidth || 400;

        setWidth(currentWidth => {
          if (Math.abs(newWidth - currentWidth) <= 60) {
            return currentWidth; // Don't process small changes - keep current width
          }
          return newWidth; // Significant change - update width
        });
      }
    });

    resizeObserver.observe(postCard);

    return () => {
      resizeObserver.unobserve(postCard);
    };
  }, []);

  // Effect to update height when calculatedHeight becomes available
  useEffect(() => {
    if (calculatedHeight > 0 && (width > 0 || !isPost)) {
      setHeight(calculatedHeight);
      setIsReadyToRender(true);
    }
  }, [calculatedHeight, width]);

  const calculatedWidth = propWidth ?? 'auto';
  const carouselWidth = isPost ? width : calculatedWidth;

  if (isPost && !isReadyToRender) {
    return (
      <HuSkeleton
        sx={{
          width: '100%',
          height: '100%',
          aspectRatio: '16 / 9',
          borderRadius: 0,
        }}
      />
    );
  }

  return (
    <Carousel
      autoPlay={false}
      indicators={mediaList.length > 1}
      navButtonsAlwaysInvisible={mediaList.length === 1}
      navButtonsProps={{
        style: {
          backgroundColor: 'white',
          color: theme.palette?.textColors?.neutralText,
        },
      }}
      navButtonsWrapperProps={{
        style: {
          padding: '0 24px',
          height: height - 200,
          top: 'unset',
        },
      }}
      fullHeightHover={false}
      cycleNavigation={false}
      className={className}
      height={height}
      sx={{
        display: 'flex',
        flexDirection: 'column',
        justifyContent: 'center',
        maxWidth: '100%',
        width: carouselWidth,
        margin: isPost ? '0 auto' : undefined,
        '& > div > div > div > div > div': {
          display: 'flex',
          justifyContent: 'center',
        },
        '& > div': {
          '&:hover button': {
            opacity: 'unset !important',
          },
        },
        '& > div > button': {
          '&:hover': {
            opacity: '0.8 !important',
          },
        },
        ...sx,
      }}
      indicatorIconButtonProps={{
        style: {
          color: theme.palette?.hugoBackground?.primaryBgLighter,
        },
      }}
      activeIndicatorIconButtonProps={{
        style: {
          color: theme.palette?.buttons?.buttonPrimaryEnabled,
        },
      }}
    >
      {mediaList.map(media => (
        <Media
          key={media.url}
          media={media}
          mediaList={mediaList}
          height={height}
          width={isPost ? width : undefined}
          onDownload={onDownload}
          grantVideoDownload={grantVideoDownload}
        />
      ))}
    </Carousel>
  );
};

const MediaCarouselThemeProvider = (props: MediaCarouselProps) => {
  const HugoThemeProvider = useHuGoTheme();

  return (
    <HugoThemeProvider>
      <MediaCarousel {...props} />
    </HugoThemeProvider>
  );
};

export default memo(MediaCarouselThemeProvider);
