import React, {memo, useCallback, useState} from 'react';
import {ImageUrl} from '@interfaces/generic';

import {CarouselImageModal} from '../CarouselImageModal';
import {Image, ImageProps} from '../Image';
import {ImageModal} from '../ImageModal';

interface Props extends ImageProps {
  images?: ImageUrl[];
  rounded?: boolean;
  showOptionsMenu?: boolean;
}

function ImageWithZoom({
  images,
  onPress,
  rounded,
  source,
  showOptionsMenu = true,
  ...props
}: Props) {
  const [showModal, setShowModal] = useState(false);
  const carouselIndex = images?.findIndex(image => image.url === source.uri);

  const onPressImage = useCallback(() => {
    setShowModal(true);
    onPress?.();
  }, [onPress]);

  const onCloseModal = useCallback(() => setShowModal(false), []);

  return (
    <>
      <Image onPress={onPressImage} source={source} {...props} />
      {images && images.length > 1 ? (
        <CarouselImageModal
          showOptionsMenu={showOptionsMenu}
          onClose={onCloseModal}
          images={images}
          index={carouselIndex}
          showZoom={showModal}
        />
      ) : (
        <ImageModal
          showOptionsMenu={showOptionsMenu}
          onClose={onCloseModal}
          rounded={rounded}
          showZoom={showModal}
          source={source}
        />
      )}
    </>
  );
}

const MemorizedImageWithZoom = memo(ImageWithZoom);
export {MemorizedImageWithZoom as ImageWithZoom};
