import React from 'react';
import {View} from 'react-native';
import {IconX} from '@tabler/icons-react-native';
import {GiphyMediaView, GiphyMedia} from '@giphy/react-native-sdk';
import {IconButton} from '@components';
import PreviewAttachment from '@components/_custom/PreviewAttachment';
import {Attachment, AttachmentType} from '@interfaces/attachments';
import {
  UploadedVideo,
  UploadedImage,
} from '@shared/components/_custom/AddComment/interfaces';

import {styles} from './styles';

interface MediaDisplayerProps {
  gif: Nullable<GiphyMedia>;
  attachments: (UploadedImage | UploadedVideo)[];
  handleDeleteImage: (image: UploadedImage) => void;
  handleDeleteVideo: (image: UploadedVideo) => void;
  handleDeleteGif: () => void;
  isFocused: boolean;
}

function MediaDisplayer({
  gif,
  attachments,
  handleDeleteImage,
  handleDeleteVideo,
  handleDeleteGif,
  isFocused,
}: MediaDisplayerProps) {
  const onDeleteImage = (attachment: UploadedImage) => () =>
    handleDeleteImage(attachment);

  const onDeleteVideo = (attachment: UploadedVideo) => () =>
    handleDeleteVideo(attachment);

  const handleDelete = (attachment: Attachment) => () => {
    if (attachment.type === AttachmentType.IMAGE) {
      onDeleteImage(attachment as UploadedImage)();
    } else if (attachment.type === AttachmentType.VIDEO) {
      onDeleteVideo(attachment as UploadedVideo)();
    }
  };

  return gif || attachments.length ? (
    <>
      {gif && (
        <View style={[styles.gifContainer, styles.commonSize]}>
          <View style={styles.gifMediaContainer}>
            <GiphyMediaView media={gif} style={styles.commonSize} />
          </View>
          <View style={styles.deleteButtonContainer}>
            <IconButton onPress={handleDeleteGif} Icon={IconX} size="sm" />
          </View>
        </View>
      )}
      {attachments && (
        <View
          style={[
            styles.attachmentsContainer,
            !isFocused && styles.attachmentsContainerFocused,
          ]}>
          {attachments.map((attachment, index) => (
            <PreviewAttachment
              onDelete={handleDelete(attachment as Attachment)}
              key={index}
              {...(attachment as Attachment)}
            />
          ))}
        </View>
      )}
    </>
  ) : null;
}

export default MediaDisplayer;
