import React from 'react';
import {View} from 'react-native';
import {useTranslation} from 'react-i18next';
import {IconUpload, IconX} from '@tabler/icons-react-native';
import {IconButton, Image, Pressable, Spinner} from '@components';
import {IconPlayVideo} from '@modules/chats/components';
import {useTheme} from '@shared/theme';

import {styles} from './styles';

type MediaType = 'image' | 'video';

interface Props {
  mediaType: MediaType;
  onRemoveFile: () => void;
  onPress?: () => void;
  uri: string;
  isLoading?: boolean;
  isError?: boolean;
  onRetry?: () => void;
  index?: number;
}

const MEDIA_LABELS: Record<MediaType, string> = {
  image: 'chat.files.image_one',
  video: 'chat.files.video_one',
};

export function MediaDisplayer({
  mediaType,
  onRemoveFile,
  onPress,
  uri,
  isLoading,
  isError,
  onRetry,
  index,
}: Props) {
  const {theme} = useTheme();
  const {t} = useTranslation();

  const mediaLabel = `${t(MEDIA_LABELS[mediaType])} ${(index ?? 0) + 1}`;
  const accessibilityLabel = `${mediaLabel}, ${
    isLoading ? 'Uploading' : 'Uploaded'
  }`;
  const removeAccessibilityLabel = `${t('general.eliminate')} ${mediaLabel}`;

  const isVideo = mediaType === 'video';
  const showPlayIcon = isVideo && !isLoading && !isError;

  return (
    <View style={styles.container}>
      <Pressable
        onPress={onPress}
        accessible={true}
        accessibilityLabel={accessibilityLabel}
        accessibilityRole="imagebutton"
        useGestureHandler>
        <Image
          source={{uri}}
          allowDownscaling
          recyclingKey={uri}
          timeout={15_000}
          transition={{
            duration: 100,
          }}
          style={[
            styles.thumbnail,
            {
              backgroundColor: theme.background.elements.brand,
            },
          ]}
          accessibilityElementsHidden
        />
        {isLoading && (
          <View style={styles.overlayContainer} accessibilityElementsHidden>
            <Spinner />
          </View>
        )}
        {showPlayIcon && (
          <View style={styles.overlayContainer} accessibilityElementsHidden>
            <IconPlayVideo />
          </View>
        )}
      </Pressable>
      {isError && (
        <View style={styles.overlayContainer}>
          <IconButton
            Icon={IconUpload}
            onPress={onRetry}
            size="sm"
            hitSlop={16}
            accessibilityLabel={t('general.retry')}
            useGestureHandler
          />
        </View>
      )}
      <View style={styles.closeContainer}>
        <IconButton
          Icon={IconX}
          onPress={onRemoveFile}
          size="sm"
          variant="tertiary"
          backgroundColor={theme.action.background.neutral.hover}
          iconColor={theme.text.neutral.default}
          accessibilityLabel={removeAccessibilityLabel}
          useGestureHandler
        />
      </View>
    </View>
  );
}
