import React, { useState, useEffect } from 'react';
import { View, ActivityIndicator, TouchableOpacity, Platform, Image } from 'react-native';
import { FileSystem } from 'src/utils';
import { Colors } from 'src/theme';
import { CACHED_ATTACHMENTS_DIR } from 'src/constants/constants';
import { API_HOST, APP_VERSION } from 'src/constants';
import { styles } from '../ChatScreen/styles';

const RenderMessageImage = ({
  props,
  token,
  currentUserId,
  onLongPress,
  setSelectedMedia
}: {
  props: any;
  token: string;
  currentUserId: number;
  onLongPress: (currentMessage: any, props: any) => any;
  setSelectedMedia: (media: string) => void;
}) => {
  const { currentMessage } = props;
  const leftMessage = currentMessage?.user?._id !== +currentUserId;
  const fileUri = `${CACHED_ATTACHMENTS_DIR}${currentMessage.attachment?.filename}`;

  const [isCached, setIsCached] = useState(false);
  const [imageLoading, setImageLoading] = useState(true);

  const [retryKey, setRetryKey] = useState(Date.now());
  const [retryCount, setRetryCount] = useState(0);
  const MAX_RETRIES = 10;

  useEffect(() => {
    const checkCache = async () => {
      try {
        const fileInfo = await FileSystem.getInfoAsync(fileUri);
        setIsCached(fileInfo.exists && fileInfo.size > 1024);
      } catch (error) {
        setIsCached(false);
      }
    };

    checkCache();
  }, [currentMessage.attachment?.filename]);

  const handleOpenImage = async (uri: string, fileName: string) => {
    const dirExist = await FileSystem.getInfoAsync(CACHED_ATTACHMENTS_DIR);
    if (!dirExist.exists) {
      await FileSystem.makeDirectoryAsync(CACHED_ATTACHMENTS_DIR, { intermediates: true });
    }

    const fileUri = `${CACHED_ATTACHMENTS_DIR}${fileName}`;

    const fileExists = await FileSystem.getInfoAsync(fileUri);
    if (fileExists.exists && fileExists.size > 1024) {
      setSelectedMedia(fileUri);

      return;
    }
    setSelectedMedia(uri);

    await FileSystem.downloadAsync(uri, fileUri, {
      headers: { Nmtoken: token, 'App-Version': APP_VERSION, Platform: Platform.OS }
    });
  };

  return (
    <TouchableOpacity
      onPress={() => {
        if (
          currentMessage.attachment.attachment_full_url &&
          !currentMessage.attachment.attachment_full_url?.startsWith('/')
        ) {
          setSelectedMedia(currentMessage.attachment.attachment_full_url);
          return;
        }
        if (
          !currentMessage.attachment.attachment_full_url?.startsWith('/') &&
          currentMessage.attachment?.local_uri
        ) {
          setSelectedMedia(currentMessage.attachment.local_uri);
          return;
        }
        handleOpenImage(
          API_HOST + currentMessage.attachment.attachment_full_url,
          currentMessage.attachment?.filename
        );
      }}
      onLongPress={() => onLongPress(currentMessage, props)}
      style={styles.imageContainer}
      disabled={currentMessage.isSending}
    >
      <Image
        key={`${currentMessage.image}-${retryKey}`}
        source={{
          uri: isCached ? fileUri : currentMessage.image,
          headers: { Nmtoken: token, 'App-Version': APP_VERSION, Platform: Platform.OS }
        }}
        loadingIndicatorSource={{ uri: isCached ? fileUri : currentMessage.image }}
        style={styles.chatImage}
        resizeMode="cover"
        onLoadStart={() => {
          if (isCached) return;
          setImageLoading(true);
        }}
        onLoad={() => {
          setTimeout(() => {
            setImageLoading(false);
          }, 100);
          setRetryCount(0);
        }}
        onLoadEnd={() => setImageLoading(false)}
        onError={() => {
          if (retryCount < MAX_RETRIES) {
            setTimeout(() => {
              setRetryKey(Date.now());
              setRetryCount((c) => c + 1);
            }, 1000);
          }
        }}
      />

      {currentMessage.isSending || imageLoading ? (
        <View
          style={{
            position: 'absolute',
            top: 0,
            left: 0,
            right: 0,
            bottom: 0,
            justifyContent: 'center',
            alignItems: 'center'
          }}
        >
          <ActivityIndicator
            size="large"
            color={leftMessage ? Colors.DARK_BLUE : Colors.FILL_LIGHT}
          />
        </View>
      ) : null}
    </TouchableOpacity>
  );
};

export default RenderMessageImage;
