import React from 'react';
import {ImageProps} from 'react-native';
import AutoHeightImage from 'react-native-auto-height-image';
import {IImageInfo} from 'react-native-image-zoom-viewer/built/image-viewer.type';
import {windowDimensions} from '@shared/constants';
import DeleteButton from '@components/DeleteButton';
import {
  calculateMaxHeight,
  getPaddingTop,
} from '@components/MultimediaContainer/utils';
import {Attachment, AttachmentType} from '@interfaces/attachments';
import {ImageWithZoom} from '@components/Image';

import {styles} from './styles';

interface Props {
  image: Attachment;
  onDeleteImage?: (urlType: string, url: string) => void;
  width: number;
  smallWidth?: number;
  multimediaWidth?: number | string | boolean;
  attachments: Attachment[];
  isComment?: boolean;
  handleDeleteImage: (image: Attachment) => void;
  imageProps?: Omit<ImageProps, 'source'>;
}

function Image({
  image,
  onDeleteImage,
  width,
  smallWidth,
  multimediaWidth,
  attachments,
  isComment,
  handleDeleteImage,
  imageProps,
}: Props) {
  const maxHeight =
    calculateMaxHeight({attachments, smallWidth, isComment}) - 20;
  const imageUrls = attachments.filter(
    file => file.type === AttachmentType.IMAGE,
  ) as IImageInfo[];

  return onDeleteImage ? (
    <>
      <AutoHeightImage
        width={smallWidth || width || windowDimensions.width}
        source={{uri: image.path || image.url}}
        style={[
          styles.container,
          !!smallWidth && styles.marginRight,
          {maxHeight},
        ]}
      />
      <DeleteButton
        top={
          smallWidth
            ? 10
            : image.width && image.height
            ? getPaddingTop({
                item: {width: image.width, height: image.height},
                attachments,
                width: width + 20,
                isComment,
              })
            : 0
        }
        right={smallWidth ? 13 : multimediaWidth ? 25 : 10}
        onPress={() => handleDeleteImage(image)}
      />
    </>
  ) : (
    <ImageWithZoom
      pinchable
      cached={false}
      source={{uri: (image.url || image.path)!}}
      imageUrls={imageUrls}
      resizeMode={isComment ? 'contain' : 'cover'}
      style={{
        height:
          ((image.height || 1) * windowDimensions.width) / (image.width || 1),
      }}
      {...imageProps}
    />
  );
}

export default Image;
