import {COMMENT_WIDTH} from '@components/PostCommentItem/constants';
import {Attachment, AttachmentType} from '@interfaces/attachments';
import {windowDimensions} from '@shared/constants';

import {DEFAULT_EXTRA_HEIGHT} from './constants';

interface MaxHeightInterface {
  attachments: Attachment[];
  smallWidth?: number;
  extraHeight?: number;
  isComment?: boolean;
}

const getMinHeight = (smallWidth?: number) =>
  smallWidth || windowDimensions.width;
// min height is the width of the screen, to ensure videos are 1:1

const getMaxHeight = (
  smallWidth?: number,
  extraHeight = DEFAULT_EXTRA_HEIGHT,
) => smallWidth || 440 + extraHeight;

export const calculateMaxHeight = ({
  attachments,
  smallWidth,
  extraHeight = DEFAULT_EXTRA_HEIGHT,
  isComment,
}: MaxHeightInterface) => {
  let maxHeight = 0;
  for (let i = 0; i < attachments.length; i++) {
    const item = attachments[i];
    if (item.type === AttachmentType.IMAGE && item.height && item.width) {
      const height =
        (item.height *
          (smallWidth ||
            (isComment
              ? COMMENT_WIDTH + DEFAULT_EXTRA_HEIGHT
              : windowDimensions.width))) /
        item.width;
      if (height > maxHeight) {
        maxHeight = height;
      }
    }
  }
  if (maxHeight === 0) {
    return getMinHeight(smallWidth);
  }
  const maxHeightValue = getMaxHeight(smallWidth, extraHeight);
  if (maxHeight > maxHeightValue) {
    return maxHeightValue;
  }
  return maxHeight + DEFAULT_EXTRA_HEIGHT;
};

export const getPaddingTop = ({
  item,
  attachments,
  width = windowDimensions.width,
  isComment,
}: {
  item: {
    width: number;
    height: number;
  };
  attachments: Attachment[];
  width?: number;
  isComment?: boolean;
}) => {
  const imageHeight = (item.height * width) / item.width;
  const maxHeight = calculateMaxHeight({attachments, isComment});
  const difference =
    maxHeight - (imageHeight <= maxHeight ? imageHeight : maxHeight);
  return (
    DEFAULT_EXTRA_HEIGHT +
    (difference > DEFAULT_EXTRA_HEIGHT ? difference / 2 : difference)
  );
};
