import React, {useCallback} from 'react';
import {Pressable, View} from 'react-native';
import {ScrollView} from 'react-native-gesture-handler';
import {IconPlayerPlay, IconX} from '@tabler/icons-react-native';
import Video, {ResizeMode} from '@components/_core/RNVideo';
import {Image} from '@components/_core/Image';
import {Attachment, AttachmentType} from '@interfaces/attachments';
import {useTheme} from '@shared/theme';

import {styles} from './styles';

interface Props {
  multimedia: Attachment[];
  onDeleteMultimedia: (attachment: Attachment) => void;
}

export function MultimediaDisplayer({multimedia, onDeleteMultimedia}: Props) {
  const {iconSizes, theme} = useTheme();

  const renderItem = useCallback(
    (item: Attachment) => {
      const source = {uri: item.path || item.url};
      const onPressDelete = () => onDeleteMultimedia(item);
      return (
        <View key={`${item.id}`}>
          {item.type === AttachmentType.IMAGE ? (
            <Image source={source} style={styles.multimedia} />
          ) : (
            <View style={styles.multimedia}>
              {item.thumbnailUrl ? (
                <Image
                  source={{uri: item.thumbnailUrl}}
                  style={styles.multimedia}
                />
              ) : (
                <Video
                  muted
                  paused
                  resizeMode={ResizeMode.COVER}
                  source={source}
                  style={styles.video}
                />
              )}
              <View style={styles.playButton}>
                <IconPlayerPlay color={theme.white} size={iconSizes.x6} />
              </View>
            </View>
          )}
          <Pressable
            hitSlop={8}
            onPress={onPressDelete}
            style={[styles.deleteButton, {backgroundColor: theme.primary}]}>
            <IconX color={theme.white} size={iconSizes.x3} />
          </Pressable>
        </View>
      );
    },
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [onDeleteMultimedia],
  );

  return (
    <ScrollView
      horizontal
      bounces={multimedia.length !== 1}
      contentContainerStyle={styles.container}
      showsHorizontalScrollIndicator={false}>
      {multimedia.map(renderItem)}
    </ScrollView>
  );
}
