import React from 'react';
import {FlatList, ListRenderItem} from 'react-native';
import FileViewer from 'react-native-file-viewer';
import {MediaEntity, MediaType} from '@modules/chats/interfaces';
import {FileDisplayer} from '@modules/chats/components';
import {useTheme} from '@shared/theme';

import {MediaDisplayer} from '../MediaDisplayer';
import {styles} from './styles';

const fileKeyExtractor = (item: MediaEntity) => item.id;

const getMediaUri = (item: MediaEntity): string => {
  if (item.type === MediaType.VIDEO) {
    return item.fileAsset?.thumbnailUrl ?? '';
  }
  return item.localUri;
};

interface Props {
  files: MediaEntity[];
  onRemoveFile: (id: string) => void;
  onRetryFile: (id: string) => void;
}

export function MultimediaContainerFooter({
  files,
  onRemoveFile,
  onRetryFile,
}: Props) {
  const {theme} = useTheme();

  const onPressFile = (file: MediaEntity) => {
    if (file.localUri) {
      FileViewer.open(file.localUri);
    }
  };

  const renderItem: ListRenderItem<MediaEntity> = ({item, index}) => {
    const isError = item.status === 'failed';
    const isLoading = item.status !== 'uploaded' && !isError;

    if (item.type === MediaType.IMAGE || item.type === MediaType.VIDEO) {
      return (
        <MediaDisplayer
          mediaType={item.type === MediaType.IMAGE ? 'image' : 'video'}
          uri={getMediaUri(item)}
          index={index}
          isLoading={isLoading}
          isError={isError}
          onRemoveFile={() => onRemoveFile(item.id)}
          onRetry={() => onRetryFile(item.id)}
        />
      );
    }

    if (item.type === MediaType.FILE) {
      return (
        <FileDisplayer
          fileName={item.name}
          bytesSize={item.sizeInBytes}
          isLoading={isLoading}
          showDownload={isError}
          onRemoveFile={() => onRemoveFile(item.id)}
          onPress={() => (isError ? onRetryFile(item.id) : onPressFile(item))}
        />
      );
    }

    return null;
  };

  return files.length ? (
    <FlatList
      horizontal
      keyExtractor={fileKeyExtractor}
      data={files}
      renderItem={renderItem}
      style={{
        backgroundColor: theme.background.layout.tertiary,
      }}
      contentContainerStyle={styles.container}
      showsHorizontalScrollIndicator={false}
      removeClippedSubviews={false}
    />
  ) : null;
}
