import React, {useState} from 'react';
import ImageViewer from 'react-native-image-zoom-viewer';
import {ImageUrl} from '@interfaces/generic';
import {useTheme} from '@shared/theme';

import {Image, ImageProps} from '../Image';
import {
  ImageModalContainer,
  ImageModalContainerProps,
} from '../ImageModalContainer';

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

const renderImage = (props: ImageProps) => <Image {...props} />;

export interface CarouselImageModalProps
  extends Omit<ImageModalContainerProps, 'children' | 'source'> {
  images: ImageUrl[];
  index?: number;
}

export function CarouselImageModal({
  images,
  index,
  onClose,
  showZoom,
}: CarouselImageModalProps) {
  const {theme} = useTheme();
  const [currentIndex, setCurrentIndex] = useState(index);
  const currentImage = {uri: images[currentIndex || 0].url};

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

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