import React from 'react';
import {View, useWindowDimensions} from 'react-native';
import {ImageWithZoom} from '@components';
import {Attachment, AttachmentType} from '@interfaces/attachments';
import {SPACING} from '@shared/theme';

import {styles, MIN_IMAGE_HEIGHT, MAX_IMAGE_HEIGHT_RATIO} from './styles';

interface ImageHeightParams {
  imgWidth?: number | null;
  imgHeight?: number | null;
  containerWidth: number;
  viewportHeight: number;
}

export const getImageHeight = ({
  imgWidth,
  imgHeight,
  containerWidth,
  viewportHeight,
}: ImageHeightParams) => {
  const maxHeight = viewportHeight * MAX_IMAGE_HEIGHT_RATIO;

  if (!imgWidth || !imgHeight) {
    return Math.min(containerWidth, maxHeight);
  }

  const calculatedHeight = (containerWidth * imgHeight) / imgWidth;
  return Math.max(MIN_IMAGE_HEIGHT, Math.min(calculatedHeight, maxHeight));
};

interface QuestionAttachmentsProps {
  attachments?: Attachment[];
  contentFit?: 'contain' | 'cover';
}

function QuestionAttachments({
  attachments,
  contentFit,
}: QuestionAttachmentsProps) {
  const {width: screenWidth, height: screenHeight} = useWindowDimensions();
  const containerWidth = screenWidth - SPACING.x2 * 2;

  const imageAttachments = attachments?.filter(
    attachment => attachment.type === AttachmentType.IMAGE,
  );

  const imageUrls = imageAttachments?.map(attachment => ({
    url: attachment.url,
  }));

  if (!imageAttachments?.length) {
    return null;
  }

  return (
    <View style={styles.attachmentsContainer}>
      {imageAttachments.map(attachment => (
        <ImageWithZoom
          showOptionsMenu={false}
          key={attachment.id}
          source={{uri: attachment.url}}
          style={[
            styles.attachmentImage,
            {
              height: getImageHeight({
                imgWidth: attachment.width,
                imgHeight: attachment.height,
                containerWidth,
                viewportHeight: screenHeight,
              }),
            },
          ]}
          images={imageUrls}
          contentFit={contentFit}
        />
      ))}
    </View>
  );
}

export default QuestionAttachments;
