import React, {useState} from 'react';
import ImageViewer from 'react-native-image-zoom-viewer';
import {ImageProps} from 'react-native';
import {
  ImageModalContainer,
  ImageModalContainerProps,
} from '@components/Image/components/ImageModalContainer';
import {Image} from '@components/Image';
import {ImageUrl} from '@interfaces/generic';
import {COLORS} from '@shared/colors';

const EmptyComponent = () => <></>;

export interface CarouselImageModalProps
  extends Omit<ImageModalContainerProps, 'children' | 'source'> {
  imageUrls: ImageUrl[];
  index?: number;
  cached?: boolean;
  showZoom: boolean;
  rounded?: boolean;
}

export function CarouselImageModal({
  imageUrls,
  cached,
  onClose,
  index,
  ...props
}: CarouselImageModalProps) {
  const [currentIndex, setCurrentIndex] = useState(index);
  const currentImage = {uri: imageUrls[currentIndex || 0].url};

  const onCloseModal = () => {
    onClose?.();
    // Reset to initial value to avoid wrong image bug
    setCurrentIndex(index);
  };

  const renderImage = ({source, ...rest}: ImageProps) => (
    <Image cached={cached} source={source!} {...rest} />
  );

  return (
    <ImageModalContainer
      source={currentImage}
      onClose={onCloseModal}
      {...props}>
      <ImageViewer
        useNativeDriver
        enableSwipeDown
        onChange={setCurrentIndex}
        imageUrls={imageUrls}
        onCancel={onCloseModal}
        renderImage={renderImage}
        renderIndicator={EmptyComponent}
        index={index}
        renderHeader={EmptyComponent}
        renderFooter={EmptyComponent}
        saveToLocalByLongPress={false}
        onSwipeDown={onCloseModal}
        backgroundColor={COLORS.TRANSPARENT}
      />
    </ImageModalContainer>
  );
}
