import React, { useEffect, useRef, useState } from "react";
import {
  StyleSheet,
  View,
  Image,
  Text,
  StatusBar,
  FlatList,
  BackHandler,
  Alert,
} from "react-native";
import {
  ACTIVITY_TYPE_MOTOR_CVOD_PRE_INSPECTION_SELF_SURVEY,
  CHASSIS_NUMBER,
  SCREEN_HEIGHT,
  SCREEN_WIDTH,
  SELFI_IMAGE_HN,
  VIDEO_TITLE_HN,
  SELFI_IMAGE,
  VIDEO_TITLE,
} from "react-native-digitcamera/src/common/Constants";
import { translate } from "react-native-digitcamera/src/common/localize/i18n";
import Orientation from "../../../react-native-orientation";
import Geolocation from "@react-native-community/geolocation";
import { getTimeZone } from "react-native-localize";
import { TouchableOpacity } from "react-native-gesture-handler";
import RNFetchBlob from "rn-fetch-blob";
import { SELFSURVEYSERVICE_DOCUMENT_URL } from "react-native-digitcamera/src/Api/ApiUrls";
import ViewShot, { captureRef } from "react-native-view-shot";
import VideoPlayer from "react-native-video-player";
import Header from "./Header";
import { PrimaryButton, Spinner } from "../common/ThemedComponents";
import Database from "../../../../Components/common/DAsyncStorage";
import { useSelector, useDispatch } from "react-redux";
import NetInfo from "@react-native-community/netinfo";
import { poseDetection } from "react-native-digitcamera/src/common/Services/poseDetection";

import reactotron from "reactotron-react-native";
import { chassiesPoseDetetction } from "react-native-digitcamera/src/common/Services/chassisPoseDetection";
import Modal from "../common/Modal";
import DeviceInfo from "react-native-device-info";
const { getImei } = require("react-native-imei");
// import moment from "moment";
import {
  errorRecord,
  firebaseAttributes,
} from "react-native-digitcamera/src/common/libEventLog/libCrashlytics/libCrashlyticsEvent";

import {
  UELogEvent,
  UELogMessage,
} from "../common/libEventLog/UserExperior/LibUserExperior";

import debounce from "lodash.debounce";
const DEBOUNCE_INTERVAL = 500;

var RealmData;
const retake = require("../common/Image/retake.png");
const proceed = require("../common/Image/proceed.png");
const no_internet = require("../common/Image/no_internet.png");

let noOfImagesPoseDetedImages = 0;
// let poseDetectionFailedImageCount = 0;
// let tempUploadImageImageCount = 0;
const InvalidImages = ({ navigation, route }) => {
  const { isLast } = route.params;

  let poseDetectionFailedImageCount = 0;
  let tempUploadImageImageCount = 0;

  const imageref = useRef();
  const [isInternetConnected, SetIsInternetConnected] = useState(true);
  // const [poseDetectionFailedImageCount, SetPoseDetectionFailedImageCount] = useState(0);
  // const [tempUploadImageImageCount, SetTempUploadImageImageCount] = useState(0);
  const [onRetryClick, SetOnRetryClick] = useState(false);
  const [isLoading, SetIsLoading] = useState(true);

  const dispatch = useDispatch();
  const RetryCountData = useSelector((state) => state.RetryCountData);
  const RetryImageData = useSelector((state) => state.RetryImageData);
  const UploadImageData = useSelector((state) => state.UploadImageData);

  const [, updateState] = React.useState();
  const [APILevel, SetAPILevel] = useState("");
  const [IMEI, SetIMEI] = useState("");
  const [deviceName, SetDeviceName] = useState("");
  const [MAC, SetMAC] = useState("");
  const [IP, SetIP] = useState("");
  const [RetryInstruction, setRetryInstruction] = useState([]);
  const [isposeDetectionCompleted, setIsposeDetectionCompleted] =
    useState(false);

  const forceUpdate = React.useCallback(() => updateState({}), []);
  var index = 0;

  let IncorrectImageCount = RetryImageData.retryImageInfo.length;
  var interval;
  useEffect(() => {
    const checkLanguage = async () => {
      RealmData = await Database.get("SelectedLang");
    };
    checkLanguage();

    const check = async () => {
      var RealmRetryInstructionData = await Database.get("PIOfflineData");
      var PIPoseDetectionCompleted = await Database.get(
        "PIPoseDetectionCompleted"
      );
      noOfImagesPoseDetedImages =
        PIPoseDetectionCompleted?.poseDetectionCompletedCount + 1;
      var PIGonePoseDetection = await Database.get("PIGonePoseDetection");
      console.log(
        "@@@@@@@@@@@@",
        RetryInstruction.length,
        PIGonePoseDetection?.GoneposeDetectionCount,
        PIPoseDetectionCompleted?.poseDetectionCompletedCount
      );
      if (
        noOfImagesPoseDetedImages >= PIGonePoseDetection?.GoneposeDetectionCount
      ) {
        SetIsLoading(false);
        setRetryInstruction(RetryImageData.retryImageInfo);
        setIsposeDetectionCompleted(true);
        clearInterval(interval);
        if (RetryImageData.retryImageInfo.length === 0) {
          // If posedetection completes with all valid images, then it should go to Upload images
          // navigation.navigate("Progress", {
          //   TotalImage: PIclickedCount?.clickedCount,
          // });
        }
      } else {
        SetIsLoading(true);
        setIsposeDetectionCompleted(false);
      }
    };
    interval = setInterval(() => {
      check();
    }, 3000);

    // checkPoseDetection()
    let unsubscribe = navigation.addListener("focus", () => {
      Orientation.lockToPortrait();
    });
    let netInfoSubscription = NetInfo.addEventListener((state) => {
      if (state.isInternetReachable) {
        SetOnRetryClick(true);
        UELogMessage("Internet Reachable", {
          "Net Info": JSON.stringify(state.details),
        });
      } else {
        UELogMessage("Internet Not Reachable", {
          "Net Info": JSON.stringify(state.details),
        });
        SetIsInternetConnected(false);
        SetOnRetryClick(false);
      }
    });
    offlineLoderclose(); // for loder off

    // disabled back handler
    const backHandler = BackHandler.addEventListener(
      "hardwareBackPress",
      () => {
        return true;
      }
    );
    return () => {
      unsubscribe();
      netInfoSubscription();
      backHandler.remove();
    };
  }, [RetryInstruction]);
  const checkPoseDetection = async () => {
    var PIVechicleData = await Database.get("PIVechicleData");
    var PIRetryCount = await Database.get("PIRetryCount");
    var AppLoginStatus = await Database.get("AppLoginStatus");

    const activityTypeId = PIVechicleData?.activityTypeId;

    UELogEvent("Check Pose Detection started in InvalidImages");

    try {
      for (index = 0; index <= IncorrectImageCount - 1; index++) {
        if (
          RetryInstruction[index]?.title == SELFI_IMAGE ||
          RetryInstruction[index]?.titleHn == SELFI_IMAGE_HN ||
          !!activityTypeId ==
            ACTIVITY_TYPE_MOTOR_CVOD_PRE_INSPECTION_SELF_SURVEY ||
          RetryInstruction[index]?.title == VIDEO_TITLE ||
          RetryInstruction[index]?.titleHn == VIDEO_TITLE_HN ||
          PIRetryCount?.retryCount > 0 ||
          AppLoginStatus?.userType == "OEMDealer" ||
          RetryInstruction[index]?.imageName == "SF" ||
          RetryInstruction[index]?.imageName == "CNG" ||
          RetryInstruction[index]?.imageName == "IWS"
        ) {
          await uploadImage(RetryInstruction[index]?.imagePath, index);
        } else if (RetryInstruction[index]?.imageName === CHASSIS_NUMBER) {
          callChassisPoseDetection(RetryInstruction[index]?.imagePath, index);
        } else {
          await poseDetectAndUpload(index);
        }
      }
      UELogEvent("Check Pose Detection Stopped in try");
    } catch (error) {
      UELogEvent("Check Pose Detection Stopped in Catch", {
        error: JSON.stringify(error),
      });
      firebaseAttributes(error);
      errorRecord(error);
      console.log("in checkPoseDetection() ", error);
    }
  };

  const callChassisPoseDetection = async (uri, index) => {
    var PIVechicleData = await Database.get("PIVechicleData");
    const activityId = PIVechicleData?.activityId;

    UELogEvent("CallChassisPoseDetection started...", {
      uri: JSON.stringify(uri),
      index: index,
    });
    var formdata = new FormData();
    formdata.append("file", {
      uri: uri,
      name: RetryInstruction[index]?.fileNameWithExt,
      fileName: RetryInstruction[index]?.fileName,
      type: "image/jpeg",
    });
    formdata.append("activityId", activityId);

    const ChassisPoseDetectionData = await chassiesPoseDetetction({
      body: formdata,
    });
    if (
      ChassisPoseDetectionData?.match_ratio >
      ChassisPoseDetectionData?.threshold_match_ratio
    ) {
      await uploadImage(RetryInstruction[index]?.imagePath, index);
    } else {
      RetryInstruction[index].uploaded = false;
      // SetPoseDetectionFailedImageCount(poseDetectionFailedImageCount+1)
      poseDetectionFailedImageCount++;
      offlineLoderclose(); // for loder off
    }
    UELogEvent("CallChassisPoseDetection ended");
  };

  const poseDetectAndUpload = async (index) => {
    var PIVechicleData = await Database.get("PIVechicleData");
    const activityId = PIVechicleData?.activityId;
    const activityTypeId = PIVechicleData?.activityTypeId;
    const licensePlateNumber = PIVechicleData?.licensePlateNumber;

    var formdata = new FormData();
    formdata.append("file", {
      uri: RetryInstruction[index]?.imagePath,
      name: RetryInstruction[index]?.fileNameWithExt,
      fileName: RetryInstruction[index]?.fileName,
      type: "image/jpeg",
    }),
      formdata.append("policyNumber", licensePlateNumber),
      formdata.append("activityTypeId", activityTypeId),
      formdata.append("checkQuality", true),
      formdata.append("source", "DIGITEDGE");

    UELogEvent("PoseDetectAndUpload Started", {
      formdata: JSON.stringify(formdata),
    });

    const poseDetectionData = await poseDetection({
      body: formdata,
    });

    let isBlur = poseDetectionData?.image_pose_array[0]?.is_blurred;
    let isDark = poseDetectionData?.image_pose_array[0]?.is_dark;

    let PoseStatus;
    if (isBlur && isDark) {
      PoseStatus = "Failed";
    } else if (isBlur || isDark) {
      PoseStatus = "Failed";
    } else {
      PoseStatus = "Success";
    }

    UELogEvent("PoseDetectAndUpload Pose Detection Details", {
      Failed: PoseStatus,
      isBlur: JSON.stringify(
        poseDetectionData?.image_pose_array[0]?.is_blurred
      ),
      isDark: JSON.stringify(poseDetectionData?.image_pose_array[0]?.is_dark),
    });

    console.log("IMAGE Uploaded ", !!isBlur, !!isDark, index);
    if (!isBlur && !isDark) {
      UELogEvent("UploadImage started pose detection success", {
        ImagePath: JSON.stringify(RetryInstruction[index]?.imagePath),
        index: JSON.stringify(index),
      });
      await uploadImage(RetryInstruction[index]?.imagePath, index);
    } else {
      // if Image is not uploaded then make it false
      RetryInstruction[index].uploaded = false;
      // SetPoseDetectionFailedImageCount(poseDetectionFailedImageCount+1)
      poseDetectionFailedImageCount++;
      console.log(
        "@@@@@@@ poseDetectionFailedImageCount @@",
        poseDetectionFailedImageCount
      );
      UELogEvent("Pose Detection Failed...", {
        "Pose Detection Failed Image Count": JSON.stringify(
          poseDetectionFailedImageCount
        ),
      });
      offlineLoderclose(); // for loder off
    }
  };

  const getDeviceInfo = () => {
    DeviceInfo.getDeviceName().then((deviceName) => {
      SetDeviceName(deviceName);
    });

    DeviceInfo.getMacAddress().then((mac) => {
      console.log("###################", mac);
      SetMAC(mac);
    });
    DeviceInfo.getIpAddress().then((ip) => {
      SetIP(ip);
    });

    DeviceInfo.getApiLevel().then((apiLevel) => {
      SetAPILevel(apiLevel);
      if (apiLevel > 28) {
        DeviceInfo.getAndroidId().then((androidId) => {
          SetIMEI(androidId);
        });
      } else {
        getImei().then((imeiList) => {
          console.log("sssssssssssssssssssssssss" + imeiList);
          SetIMEI(imeiList);
        });
      }
    });
  };

  const uploadImage = async (uri, itemIndex) => {
    UELogEvent("UploadImage started", {
      uri: JSON.stringify(uri),
      "item index": JSON.stringify(itemIndex),
      "Incorrect Document Uploading": JSON.stringify(
        RetryInstruction[index]?.fileName
      ),
    });
    console.log(
      "InCorrect.js  Document which uploading >>> >> > ",
      RetryInstruction[index]?.fileName
    );
    const xhr = new XMLHttpRequest();
    const formData = new FormData();
    console.log("IMAGE URI TO BE UPLOADED > > >   ", uri);

    const handleProgress = (event) => {
      reactotron.log(Math.round(event.loaded * 100) / event.total);
    };

    var PILocation = await Database.get("PILocation");
    var PIVechicleData = await Database.get("PIVechicleData");
    var PIOdometerData = await Database.get("PIOdometerData");

    currentLatitude = PILocation?.lat;
    currentLongitude = PILocation?.long;
    const documentUploadData = {
      activityId: PIVechicleData?.activityId,
      data: null,
      dataUploadStatus: 0,
      fullName: null,
      geoLocation: {
        isBlocked: "",
        deviceName: deviceName,
        latitude: currentLatitude,
        longitude: currentLongitude,
        operatingSystem: DeviceInfo.getSystemVersion(),
        timezone: "Asia/Kolkata",
        deviceTime: null,
        ipAddress: IP,
        deviceIMEI: IMEI,
        macAddress: MAC,
        documentSource: "DigitEdge",
      },
      isLast: "false",
      isLastData: "false",
      isLastDocument: "false",
      isSurveyor: "false",
      manualOdometerReading:
        RetryInstruction[index]?.imageName == "ODO"
          ? PIOdometerData?.readings
          : "",
      source: "DIGITEDGE",
    };

    formData.append("file", {
      uri: uri,
      type: "image/jpeg",
      fileName: RetryInstruction[index]?.fileName,
      name: RetryInstruction[index]?.fileNameWithExt,
    });
    formData.append("documentData", JSON.stringify(documentUploadData));

    xhr.upload.addEventListener("progress", handleProgress);
    xhr.addEventListener("load", () => {
      console.log("Uploaded");
      console.log("IMAGE STATUS  > > >", xhr.response, itemIndex);
      // if Image is not uploaded then make it true
      RetryInstruction[itemIndex].uploaded = true;
      // uploadedImageCount = uploadedImageCount + 1;
      // SetTempUploadImageImageCount(tempUploadImageImageCount+1)
      tempUploadImageImageCount++;

      offlineLoderclose(); // for loder off

      // dispatch({
      //   type: "UPLOAD_IMAGE",
      //   payload: {
      //       uploadImageCount: uploadedImageCount,
      //     },
      // });
      forceUpdate();

      UELogEvent("Uploaded Image in invalidimages.js", {
        formData: JSON.stringify(
          "Uploaded Image :" +
            RetryInstruction[index]?.fileNameWithExt +
            "\n" +
            documentUploadData
        ),
      });
      firebaseAttributes(
        "Uploaded Image :" +
          RetryInstruction[index]?.fileNameWithExt +
          "\n" +
          documentUploadData
      );
    });
    xhr.addEventListener("abort", () => {
      // if Image is not uploaded then make it false
      RetryInstruction[index].uploaded = false;
      // SetTempUploadImageImageCount(tempUploadImageImageCount+1)
      tempUploadImageImageCount++;

      offlineLoderclose(); // for loder off
      UELogEvent.log(
        "In Incorrect Images => Upload service failed with => 'abort' ",
        {
          "Image Index": JSON.stringify(index),
        }
      );
      console.log(
        "In Incorrect Images => Upload service failed with => 'abort' "
      );
    });
    xhr.addEventListener("error", () => {
      // if Image is not uploaded then make it false
      RetryInstruction[index].uploaded = false;
      // SetTempUploadImageImageCount(tempUploadImageImageCount+1)
      tempUploadImageImageCount++;
      offlineLoderclose(); // for loder off
      UELogEvent.log(
        "In Incorrect Images => Upload service failed with => 'error' ",
        {
          "Image Index": JSON.stringify(index),
        }
      );
      console.log(
        "In Incorrect Images => Upload service failed with => 'error' "
      );
    });
    xhr.addEventListener("timeout", () => {
      // if Image is not uploaded then make it false
      RetryInstruction[index].uploaded = false;
      // SetTempUploadImageImageCount(tempUploadImageImageCount+1)
      tempUploadImageImageCount++;
      offlineLoderclose(); // for loder off
      UELogEvent.log(
        "In Incorrect Images => Upload service failed with => 'timeout' ",
        {
          "Image Index": JSON.stringify(index),
        }
      );
      console.log(
        "In Incorrect Images => Upload service failed with => 'timeout' "
      );
    });
    xhr.open("POST", SELFSURVEYSERVICE_DOCUMENT_URL);
    xhr.setRequestHeader(
      "Accept",
      "*/*",
      "Content-Type",
      "multipart/form-data"
    );
    xhr.send(formData);

    var PIUploadedCount = await Database.get("PIUploadedCount");
    var uploadedImageCount = PIUploadedCount?.uploadedCount;
    uploadedImageCount = uploadedImageCount + 1;
    update = async () => {
      await Database.update("PIUploadedCount", {
        uploadedCount: uploadedImageCount,
      });
    };
    update();

    return 0;
  };

  const offlineLoderclose = () => {
    console.log(
      "IncorrectImageCount =>",
      IncorrectImageCount,
      " tempUploadImageImageCount => ",
      tempUploadImageImageCount,
      " poseDetectionFailedImageCount => ",
      poseDetectionFailedImageCount
    );
    if (
      tempUploadImageImageCount + poseDetectionFailedImageCount >=
      IncorrectImageCount
    ) {
      SetIsLoading(false);
    }
    // if (tempUploadImageImageCount >= IncorrectImageCount) {
    //   navigation.navigate("Progress");
    //   IncorrectImageCount = 0; // setting back to zero
    // }
  };

  const addDataToredux = async () => {
    dispatch({
      type: "RETRY_COUNT",
      payload: {
        retryCount: Number(RetryCountData.retryCountInfo.retryCount) + 1,
        index: 0,
        isAddNewImageData: true,
      },
    });

    var PIRetryCount = await Database.get("PIRetryCount");
    let piRetryCount = PIRetryCount?.retryCount;
    await Database.update("PIRetryCount", {
      retryCount: piRetryCount + 1,
      index: 0,
      isAddNewImageData: true,
    });

    Database.update("PIINDEX", {
      lastIndex: 0,
    });

    dispatch({
      type: "LAST_DATA",
      payload: {
        isLast: false,
      },
    });
    let retryData = { retryImageInfo: [] };
    console.log("RetryInstruction  ", RetryInstruction);
    RetryInstruction?.filter((item) => {
      console.log("item.uploaded == false", item.uploaded == false);
      if (item.uploaded == false) {
        console.log("IMAGE NOT UPLOADED  >>>", item);
        retryData.retryImageInfo.push(item);
      } else {
        console.log("IMAGE WWWWWWWWWWWWWWWWW UPLOADED  >>>", item);
      }
    });

    console.log("))))))))))))))))))))))))))))))))))", retryData);

    await Database.remove("PIOfflineData");
    var PIRetryCount = await Database.get("PIRetryCount");

    Database.set("PIOfflineData", {
      retryImageData: JSON.stringify(retryData),
    });

    console.log(
      "!!!!!!!!!!!!!!!!!!!!!!!!",
      retryData.retryImageInfo.length,
      PIRetryCount?.retryCount
    );
    setRetryInstruction([]);
    // clearing data before going PI SCREEN
    // When we land on PI SCreen At that time we will get Clean Redux With NO Values
    // We are storing all Redux value in realm and We are using it from there only...
    dispatch({
      type: "CLEAR_RETRY_IMAGE_STATE",
    });

    // if (
    //   retryData.retryImageInfo.length == 0 ||
    //   PIRetryCount?.retryCount > 2
    // ) {
    //   navigation.navigate("Progress");
    //   IncorrectImageCount = 0; // setting back to zero
    // } else {
    //   navigation.navigate("PI");
    //   IncorrectImageCount = 0; // setting back to zero
    // }

    // If there are 0 incorrect images, move them to upload i.e. Progress.js
    if (IncorrectImageCount - tempUploadImageImageCount <= 0) {
      navigation.navigate("Progress");
      IncorrectImageCount = 0; // setting back to zero
    } else {
      navigation.replace("PI");
      IncorrectImageCount = 0; // setting back to zero
    }
    clearInterval(interval);

    await Database.update("PIGonePoseDetection", {
      GoneposeDetectionCount: 0,
    });

    await Database.update("PIPoseDetectionCompleted", {
      poseDetectionCompletedCount: 0,
    });
  };

  const noInternetAlertUx = () => {
    return (
      <View>
        <View style={{ justifyContent: "center" }}>
          <Image
            source={no_internet}
            style={{
              resizeMode: "center",
              width: SCREEN_WIDTH - 128,
              alignItems: "center",
              height: SCREEN_HEIGHT / 3,
              marginLeft: 63,
              marginRight: 64,
            }}
          />
        </View>

        <View style={{ alignSelf: "center", marginTop: 32 }}>
          <Text style={{ fontFamily: "Muli-Regular", fontSize: 14 }}>
            {translate("Please recheck your Internet connection and Retry")}
          </Text>
        </View>
        <PrimaryButton
          style={{ margin: 24 }}
          disabled={!onRetryClick}
          onPress={() => {
            checkPoseDetection();
            if (onRetryClick) {
              SetIsInternetConnected(true);
            }
            SetIsLoading(true);
          }}
        >
          {translate("Retry")}
        </PrimaryButton>
      </View>
    );
  };

  const noInternetAlert = () => {
    return (
      <View>
        <Modal
          // isVisible={!isInternetConnected}
          isVisible={false}
          onBackdropPress={() => SetIsInternetConnected(false)}
          onClose={() => SetIsInternetConnected(true)}
          heading={"No Internet Connection"}
          isTranslate={true}
          headerImageVisible={false}
        >
          {noInternetAlertUx()}
        </Modal>
      </View>
    );
  };

  const debouncedCall = debounce(
    () => {
      console.log("Debounced");
      addDataToredux();
    },
    DEBOUNCE_INTERVAL,
    { trailing: true }
  );

  const renderItem = ({ item, index }) => {
    if (item.imagePath == "") {
      //removed blank obj.
      return null;
    } else {
      if (!item.uploaded) {
        return (
          <View>
            <View style={styles.listView}>
              {/* Image View */}
              <View style={styles.imageView}>
                <Image
                  source={{ uri: item.imagePath }}
                  style={{
                    alignSelf: "center",
                    width: SCREEN_WIDTH / 2.7,
                    height: SCREEN_WIDTH / 2.9,
                    resizeMode: "stretch",
                  }}
                />
              </View>
              {/* Blank View */}
              <View style={styles.blankView}></View>
              {/* Text View */}
              <View style={styles.textView}>
                {RealmData && (
                  <Text style={styles.heading}>
                    {RealmData?.PreferredLanguage === undefined ||
                    RealmData?.PreferredLanguage == "en"
                      ? item.title
                      : item.titleHn == undefined
                      ? "360 ° वीडियो लें"
                      : item.titleHn}
                  </Text>
                )}
                <Text style={styles.subHeadingText}>{translate(item.msg)}</Text>
              </View>
            </View>
            <View style={styles.divider}></View>
          </View>
        );
      }
    }
  };
  return (
    <View style={styles.main}>
      <StatusBar hidden={true} />
      <Spinner loading={isLoading} />

      <Header
        onlanguagechange={() => {
          forceUpdate();
        }}
        onbackPress={() => {
          navigation.goBack();
        }}
      />

      {!isposeDetectionCompleted ? (
        <>
          <View
            style={{ justifyContent: "center", alignItems: "center", flex: 1 }}
          >
            <Text style={styles.posemsgText}>
              We are processing your images please wait
            </Text>
          </View>
        </>
      ) : (
        <>
          {/* Document list  */}
          <View style={styles.subMainView}>
            <Text style={styles.oopsTitleText}>
              {translate("Oops!  ")}
              <Text style={{ fontSize: 20, color: "#000000" }}>
                {IncorrectImageCount - tempUploadImageImageCount < 0
                  ? 0
                  : IncorrectImageCount - tempUploadImageImageCount}{" "}
                {translate("Incorrect photos")}
              </Text>
            </Text>
            <Text style={styles.subText}>
              {translate(
                "Please upload the photo again! The photo uploaded is incorrect Please follow the instructions and capture it again"
              )}
            </Text>

            <FlatList
              data={RetryInstruction}
              keyExtractor={(item, index) => index.toString()}
              renderItem={renderItem}
              maxToRenderPerBatch={100}
              updateCellsBatchingPeriod={1000}
            />
          </View>
          {noInternetAlert()}
          {/* button view */}
          <View style={styles.buttonView}>
            <PrimaryButton
              onPress={() => {
                debouncedCall();
              }}
              // disabled={!isInternetConnected}
              disabled={false}
            >
              {translate("Retake")}
            </PrimaryButton>
          </View>
        </>
      )}
    </View>
  );
};
export default InvalidImages;

const styles = StyleSheet.create({
  main: {
    flex: 1,
  },
  subMainView: {
    flex: 0.9,
    margin: 24,
  },
  buttonView: {
    flex: 0.1,
    marginLeft: 24,
    marginRight: 24,
    justifyContent: "center",
  },
  oopsTitleText: {
    fontFamily: "Muli-ExtraBold",
    fontSize: 20,
    color: "red",
    marginBottom: 10,
  },
  titleText: {
    fontFamily: "Muli-ExtraBold",
    fontSize: 20,
  },
  subText: {
    fontSize: 16,
    fontFamily: "Muli-Regular",
    marginBottom: 24,
  },
  imageView: {
    flex: 0.4,
    justifyContent: "center",
    borderColor: "#DDDDDD",
    borderWidth: 1,
    borderRadius: 8,
  },
  listView: {
    flex: 1,
    flexDirection: "row",
  },
  blankView: {
    flex: 0.05,
  },
  textView: {
    flex: 0.55,
    justifyContent: "center",
  },
  divider: {
    width: SCREEN_WIDTH,
    height: 1,
    borderWidth: 1,
    marginTop: 17,
    marginBottom: 17,
    borderColor: "#DDDDDD",
  },
  heading: {
    fontSize: 16,
    fontFamily: "Muli-Bold",
    marginBottom: 10,
  },
  subHeadingText: {
    fontSize: 13,
    fontFamily: "Muli-Regular",
    color: "#444444",
  },
  posemsgText: {
    fontSize: 16,
    fontFamily: "Muli-Regular",
    textAlignVertical: "center",
  },
});
