import React, { useState, useEffect } from "react";
import { View } from "react-native";
import { Image } from "expo-image";

const DynamicImage = ({ uri, children, ...props }) => {
  const [loading, setLoading] = useState(true);
  const [numRetries, setNumRetries] = useState(0);

  useEffect(() => {
    if (numRetries < 15) {
      const timer = setTimeout(() => {
        setLoading(true);
      }, 2500);
      return () => clearTimeout(timer);
    }
  }, [numRetries]);

  const handleError = () => {
    setLoading(false);
    setNumRetries(numRetries + 1);
  };

  return (
    <View style={{ flex: 1 }}>
      {loading && numRetries < 15 && uri ? (
        <Image
          source={uri}
          contentFit="cover"
          transition={500}
          {...props}
          onError={handleError}
        />
      ) : (
        <View {...props}>{children}</View>
      )}
    </View>
  );
};

export default DynamicImage;
