import React from 'react';
import {View} from 'react-native';
import {ImageWithZoom} from '@components/_core/Image';
import {Video} from '@components/_core/Video';
import {Attachment, AttachmentType} from '@interfaces/attachments';
import {ScreenKey, usePostIsInView} from '@shared/stores/useActivePostsStore';

import {styles} from './styles';

interface Props {
  images: Attachment[];
  isActive: boolean;
  item: Attachment;
  postId?: number;
  screenKey?: Nullable<ScreenKey>;
  withAutoPlay?: boolean;
  maxHeight: number;
  containerWidth: number;
}

export function MultimediaItem({
  images,
  isActive,
  item,
  maxHeight,
  containerWidth,
  postId,
  screenKey,
  withAutoPlay,
}: Props) {
  const postInView = usePostIsInView(postId, screenKey);
  const isVisible =
    postId && postInView !== undefined ? isActive && postInView : undefined;

  const width = Math.ceil(containerWidth);
  const height = maxHeight;

  return (
    <View style={[styles.container, {width, height}]}>
      {item.type === AttachmentType.IMAGE ? (
        <ImageWithZoom
          pinchable
          source={{uri: (item.url || item.path)!}}
          images={images}
          style={{width, height}}
          contentFit="contain"
        />
      ) : (
        <Video
          isVisible={isVisible}
          video={item}
          width={width}
          style={{height}}
          withAutoPlay={withAutoPlay}
        />
      )}
    </View>
  );
}
