import React, {useMemo} from 'react';
import {Pressable} from 'react-native';
import {FilesCarousel} from '@components/_custom/FilesCarousel';
import {GifPreview} from '@components/_custom/GifPreview';
import {MultimediaContainer} from '@components/_custom/MultimediaContainer';
import {getPostBodyGifProps} from '@components/Post/components/PostBody/utils';
import {
  Attachment,
  AttachmentType,
  GifAttachment,
  RequestAttachment,
} from '@interfaces/attachments';
import {PreviewLivestreamVideo} from '@modules/livestream/components/PreviewLivestreamVideo';
import {Post} from '@modules/post/interfaces';
import {ScreenKey} from '@shared/stores/useActivePostsStore';

import {BasePost} from '../../interfaces';
import {parsePostAttachments} from '../../utils';
import {styles} from './styles';

interface Props {
  post: BasePost;
  groupId?: number;
  screenKey?: Nullable<ScreenKey>;
}

const isGifAttachment = (attachment: RequestAttachment) =>
  attachment.type === AttachmentType.GIF;

export function PostAttachments({post, groupId, screenKey}: Props) {
  const {id} = post;
  const stream = (post as Post).stream;

  const {multimedia, files, audio} = useMemo(
    () => parsePostAttachments(post.attachments),
    [post.attachments],
  );
  const nonAudioFiles = useMemo(
    () => files.filter(file => !audio.includes(file as Attachment)),
    [files, audio],
  );
  const hasMultimedia = !!multimedia?.length;
  const showLivestreamPreview = !!stream && !hasMultimedia;
  const hasGif = !!post?.attachments?.some(isGifAttachment);

  return (
    <>
      {hasGif && (
        <GifPreview
          gif={post?.attachments[0]?.externalReference}
          {...getPostBodyGifProps(post?.attachments[0] as GifAttachment, false)}
        />
      )}
      {/* The empty TouchableOpacity function is in order to
          capture the event and avoid navigating to the PostDetail
          whenever the user PinchToZoom an image. (ANDROID BUG) */}
      {showLivestreamPreview ? (
        <Pressable>
          <PreviewLivestreamVideo
            stream={stream}
            postId={post.id}
            groupId={groupId}
          />
        </Pressable>
      ) : hasMultimedia ? (
        <Pressable>
          <MultimediaContainer
            attachments={multimedia as Attachment[]}
            postId={id}
            screenKey={screenKey}
            withAutoPlay
          />
        </Pressable>
      ) : null}
      <FilesCarousel files={nonAudioFiles as Attachment[]} />
      {!!audio.length && (
        <FilesCarousel files={audio} style={styles.audioCarousel} />
      )}
    </>
  );
}
