import React from 'react';
import {ImageProps, View} from 'react-native';
import {Video} from '@components';
import {Attachment, AttachmentType} from '@interfaces/attachments';
import {usePostIsInView} from '@shared/stores/useActivePostsStore';
import {windowDimensions} from '@shared/constants';

import Image from './components/Image';
import {styles} from './styles';

const PATH = 'path';
const URI = 'uri';
const URL = 'url';

interface Props {
  item: Attachment;
  index: number;
  multimediaWidth?: number;
  width?: number;
  onDeleteImage?: (urlType: string, url: string) => void;
  onDeleteVideo?: (key: string, value: string | number) => void;
  smallWidth?: number;
  attachments: Attachment[];
  isComment?: boolean;
  editingPost?: boolean;
  withAutoPlay?: boolean;
  imageProps?: Omit<ImageProps, 'source'>;
  isActive: boolean;
  postId?: number;
}

/**
 * @deprecated Use `_custom/MultimediaContainer` instead
 */
function AttachmentItem({
  item,
  index,
  multimediaWidth,
  width,
  onDeleteImage,
  onDeleteVideo,
  smallWidth,
  attachments,
  isComment,
  editingPost,
  withAutoPlay,
  imageProps,
  isActive,
  postId,
}: Props) {
  const postInView = usePostIsInView(postId!);
  const isVisible =
    postId && postInView !== undefined ? isActive && postInView : undefined;

  const handleDeleteVideo = (video: Attachment) => {
    editingPost && video.id
      ? onDeleteVideo!('id', video.id)
      : video.uri
      ? onDeleteVideo!(URI, video.uri)
      : video.path
      ? onDeleteVideo!(PATH, video.path)
      : onDeleteVideo!(URL, video.url || '');
  };

  const handleDeleteImage = (image: Attachment) => {
    editingPost
      ? onDeleteImage?.(URL, image.url)
      : image.uri
      ? onDeleteImage?.(URI, image.uri)
      : image.path
      ? onDeleteImage?.(PATH, image.path)
      : onDeleteImage?.(URL, image.url || '');
  };

  const commonProps = {
    width: multimediaWidth || width || windowDimensions.width,
    smallWidth: smallWidth,
  };
  const widthContainer = multimediaWidth
    ? width || windowDimensions.width
    : '100%';

  return (
    <View
      key={index}
      style={[styles.overlayTouchable, {width: widthContainer}]}>
      {item.type === AttachmentType.IMAGE ? (
        <Image
          image={item}
          onDeleteImage={onDeleteImage}
          multimediaWidth={multimediaWidth}
          attachments={attachments}
          isComment={isComment}
          handleDeleteImage={handleDeleteImage}
          imageProps={imageProps}
          {...commonProps}
        />
      ) : (
        <Video
          video={item}
          handleDeleteVideo={onDeleteVideo ? handleDeleteVideo : undefined}
          withAutoPlay={withAutoPlay}
          isVisible={isVisible}
          {...commonProps}
        />
      )}
    </View>
  );
}

export default AttachmentItem;
