import { useTheme } from '@emotion/react';
import React from 'react';
import Box from '../Box';
import Typography from '../Typography';
import {
  StyledCarouselContentWrapper,
  StyledCarouselHeading,
  StyledCarouselImage,
  StyledCustomSizeCarouselImage,
} from './StyledCarousel';
import type { CarouselData, CarouselImageProps } from './types';

interface CarouselItemProps extends Omit<CarouselData, 'background'> {
  width: number;
}

function isCarouselImageProps(
  image: CarouselImageProps | string
): image is CarouselImageProps {
  return typeof image === 'object';
}

const CarouselItem = ({
  width,
  image,
  content,
  heading,
  body,
}: CarouselItemProps) => {
  const theme = useTheme();

  const ImageComponent = React.useMemo(() => {
    if (image) {
      if (isCarouselImageProps(image)) {
        return (
          <StyledCustomSizeCarouselImage
            source={image}
            themeHeight={image.height}
            themeWidth={image.width}
            themeResizeMode={image.resizeMode}
            style={{ marginBottom: theme.space.medium }}
          />
        );
      }

      return (
        <StyledCarouselImage
          source={typeof image === 'string' ? { uri: image } : image}
          style={{ marginBottom: theme.space.medium }}
        />
      );
    }

    return null;
  }, [image]);

  return (
    <Box style={{ width }}>
      {ImageComponent}

      <StyledCarouselContentWrapper paddingHorizontal="medium" width={width}>
        {content}

        {!!heading && (
          <StyledCarouselHeading level="h1" typeface="playful">
            {heading}
          </StyledCarouselHeading>
        )}

        {!!body && <Typography.Body>{body}</Typography.Body>}
      </StyledCarouselContentWrapper>
    </Box>
  );
};

export default CarouselItem;
