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,
  get4WPoseFileNames,
  DOC,
  detectOnlyPoseFileNames,
  multiplePics,
  get2WPoseFileNotDoc,
  image_pose_blur,
  image_pose_dark,
  image_pose_wrong,
  is2Wflow,
} 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";
import { offlinePIDataToRealm, updateStatusRealm } from "react-native-digitcamera/src/Screens/OfflineFlow/CommonFunc";
import UploadFile from "react-native-digitcamera/src/Screens/UploadFile";
import { getActivityid } from "react-native-digitcamera/src/common/Services/getActivityid";
const DEBOUNCE_INTERVAL = 500;

var RealmData;
var PIVechicleData;
var AppLoginStatus;
var activityId;
var activityTypeId;
var licensePlateNumber;
const retake = require("../common/Image/retake.png");
const proceed = require("../common/Image/proceed.png");
const no_internet = require("../common/Image/no_internet.png");
var PIRetryCount;
let noOfImagesPoseDetedImages = 0;
var message;

var sensorImageDetails = [];
var PILocation;

// 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 [isOfflineLoading, SetIsOfflineLoading] = useState(false);

  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(() => {
    interval = setInterval(async () => {
      RealmData = await Database.get("SelectedLang");
      PIVechicleData = await Database.get("PIVechicleData");
      AppLoginStatus = await Database.get("AppLoginStatus");
      PIRetryCount = await Database.get("PIRetryCount");
      PILocation = await Database.get("PILocation");

      activityId = PIVechicleData?.activityId;
      activityTypeId = PIVechicleData?.activityTypeId;
      licensePlateNumber = PIVechicleData?.licensePlateNumber;

      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
      ) {
        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[0]?.clickedCount,
          // });
        }
      } else {
        setIsposeDetectionCompleted(false);
      }
    }, 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 callActivityID = async () => {
    try {
      SetIsOfflineLoading(true)
      const vechicleData = await Database.get("PIVechicleData");

      let activityTypeId = vechicleData?.activityTypeId;
      let registrationNumber = vechicleData?.licensePlateNumber;
      let quoteNumber = vechicleData?.quoteNumber;
      let toTutorial = vechicleData?.toTutorial;
      let toWithQuote = vechicleData?.toWithQuote;
      //API call
      const { getUserDetails } = require("../common/Who");
      await getUserDetails();
      const {
        emailId,
        name,
        phoneNo,
        panHolderName,
        panNo,
        agentNumber,
      } = require("../common/Who");
      const AppLoginStatus = await Database.get("AppLoginStatus");
      const USERTYPE = AppLoginStatus?.userType;
      let body;

      if (USERTYPE === "Customer") {
        body = {
          activityTypeId: activityTypeId,
          customerDetailData: {
            emailId: emailId,
            name: name,
            phoneNo: phoneNo,
          },
          licensePlateNumber: registrationNumber,
          previousPolicyExpired: true,
          quoteNumber: quoteNumber,
        };
      } else if (USERTYPE === "DealerOrAgent") {
        body = {
          activityTypeId: activityTypeId,
          customerDetailData: {
            emailId: emailId,
            name: name,
            phoneNo: phoneNo,
            panHolderName: panHolderName,
            panNo: panNo,
          },
          agentId: agentNumber,
          licensePlateNumber: registrationNumber,
          previousPolicyExpired: true,
          quoteNumber: quoteNumber,
        };
      }

      console.log(
        "Invalid Images /preinspection body ",
        JSON.stringify(body, null, "  "),
        emailId,
        name,
        phoneNo,
        panHolderName,
        panNo
      );
      var activityData = await getActivityid({ body });
      registrationNumber = activityData?.additionalActivitiesList.filter(
        (item) => {
          if (item.key == "Registration Number") {
            return item;
          }
        }
      );
      let userNCB = activityData?.additionalActivitiesList.filter((item) => {
        if (item.key == "User NCB") {
          return item;
        }
      });
      dispatch({
        type: "ACTIVITY_DATA",
        payload: {
          activityId: activityData?.activityID,
          activityTypeId: activityData?.activityTypeId,
          licensePlateNumber:
            registrationNumber === undefined ? "" : registrationNumber[0].value,
          toWithQuote: toWithQuote,
          toTutorial: toTutorial,
          quoteNumber: quoteNumber,
        },
      });
      await Database.update("PIVechicleData", {
          activityId: activityData?.activityID,
          activityTypeId: activityData?.activityTypeId,
          licensePlateNumber:
            registrationNumber === undefined
              ? ""
              : registrationNumber[0].value,
          toWithQuote: toWithQuote,
          toTutorial: toTutorial,
          quoteNumber: quoteNumber,
          ncb:
            userNCB === undefined || userNCB.length == 0
              ? 0
              : Number(userNCB[0].value),
          vechicleType: "",
        });
      console.log("****** ***** **** *   Callled inavalidImages.js updateData()");
      updateData(activityData)
      SetIsOfflineLoading(false)
    } catch (error) {
      SetIsOfflineLoading(false)
      console.log("Error in callActivityID in invalidImages.js ",error);
    }
  }

  const updateData = async (activityData) => {
    activityId = activityData?.activityID;
    activityTypeId = activityData?.activityTypeId;
    licensePlateNumber = activityData?.licensePlateNumber;
  };
  const checkPoseDetection = async () => {
    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);
        }
      }
      SetIsOfflineLoading(false);
      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) => {
    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) => {
   UELogEvent("callPoseDetection api call started", {
      uri: JSON.stringify(RetryInstruction[index]?.imagePath),
    });
    let isBlur = true,
      isDark = true;
    let imgPose;
    let poseName;
    let isDetect;

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

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

    UELogEvent("Received response from poseDetection", {
      poseDetectionData: JSON.stringify(poseDetectionData),
    });

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

    poseName = await get4WPoseFileNames();

    // if image is type of document like RC/DL
    if (imgPose == DOC) {
      var isIncorrect = false;
      var poseNameNotDoc = get2WPoseFileNotDoc(); // gating Doc

      UELogMessage("image is type of document like RC/DL", {
        imgPose: JSON.stringify(imgPose),
        DOC: JSON.stringify(DOC),
        poseNameNotDoc: JSON.stringify(poseNameNotDoc),
      });

      poseNameNotDoc.forEach((item) => {
        //RCB
        if (item == DocumentImageName) {
          isIncorrect = true;
        }
      });

      if (!isIncorrect) {
        isDetect == true;
      }
    } else {
      UELogEvent("Pure images", {
        poseName: JSON.stringify(poseName),
      });
      // if it is purly images
      poseName.forEach((item) => {
        if (item == imgPose) {
          if (imgPose == DocumentImageName) {
            isDetect = true;
          }
        }
      });
    }

    if (!detectOnlyPoseFileNames().includes(imgPose) && (isBlur || isDark)) {
      isDetect = false;
    }
    console.log("isBlur", isBlur);
    console.log("isDark", isDark);

    if (!isDetect) {
      UELogEvent("is detect is false", {
        isDetect: JSON.stringify(!isDetect),
      });
      var multiCapturePose = true;
      var multiPoseName = "";

      var pose = multiplePics();
      pose.forEach((item) => {
        if (
          DocumentImageName !== undefined &&
          DocumentImageName.includes(item)
        ) {
          multiCapturePose = true;
          multiPoseName = item;
        }
      });

      if (isBlur && isDark) {
        message = image_pose_blur + " " + image_pose_dark;
        UELogMessage("image is both blur and dark", {
          isBlur: JSON.stringify(isBlur),
          isDark: JSON.stringify(isDark),
        });
      } else {
        if (isDark) message = image_pose_dark;
        if (isBlur) message = image_pose_blur;
        if (!isDark && !isBlur) message = image_pose_wrong;
      }
    }

    if (!isBlur && !isDark && isDetect) {
      UELogEvent("image is good", {
        isBlur: JSON.stringify(isBlur),
        isDark: JSON.stringify(isDark),
      });
      console.log(
        "Uploading An Image ===>",
        "isDetect=",
        isDetect,
        " imgPose=",
        imgPose,
        " DocumentImageName=",
        DocumentImageName
      );
      UELogMessage("Uploading an image", {
        isDetect: JSON.stringify(isDetect),
        imgPose: JSON.stringify(imgPose),
        DocumentImageName: JSON.stringify(DocumentImageName),
      });
      //if image is good then excute this block
      // upload image
      await uploadImage(RetryInstruction[index]?.imagePath, index);
      UELogMessage("Upload image uri", {
        uri: JSON.stringify(uri),
      });
      //create sensor data ==> if image is uploaded
      sensorImageDetails.push({
        attemptCount: PIRetryCount?.retryCount + 1,
        fileName: activityId + "_" + DocumentImageName + ".jpg",
        latitude: currentLatitude,
        longitude: currentLongitude,
        pose: DocumentImageName,
        success: true,
        timestamp: new Date().getTime(),
      });

      dispatch({
        type: "SENSOR_DETAILS",
        payload: sensorImageDetails,
      });
      console.log("IN if");
      UELogEvent("User Experior IN if", {
        sensorImageDetails: JSON.stringify(sensorImageDetails),
      });
    } 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) => {
                    let imageName = RetryInstruction[itemIndex]?.imageName;
                    let ext = imageName == "VDO" ? ".mp4" : ".jpg";
                    console.log("(((((   ",isInternetConnected,imageName,ext);
                   try {
                    if(onRetryClick)
                    {
                    UploadFile(
                      uri,
                      imageName,
                      ext,
                      () => {
                        props.navigation.navigate("WithQuote");
                      },
                      () => {
                        addSensorImageData(ext, true,itemIndex);
                      },
                      () => {
                        addSensorImageData(ext, false,itemIndex);
                      }
                    );
                    console.log(" InvalidImages.js uploadImages() activityTypeId PIRetryCount[0]?.retryCount>0 PIRetryCount[0]?.retryCount",activityTypeId,PIRetryCount[0]?.retryCount>0,PIRetryCount[0]?.retryCount>0);
                    if (is2Wflow(activityTypeId) &&PIRetryCount?.retryCount>0) {
                      navigation.navigate("VideoPIProgress")
                    }
                    }
                    else
                    {
                     await updateStatusRealm(uri,imageName,'failed')
                      offlinePIDataToRealm(true)
                    }
                   } catch (error) {
                    console.log("Error in uplodFile in InvalidImages.js ",error);
                   }
  };

  const addSensorImageData = (ext, ImageStatus, itemIndex) => {
    var currentLatitude = PILocation?.lat;
    var currentLongitude = PILocation?.long;
    let imageName = RetryInstruction[itemIndex]?.fileName;
    var attemptCount = PIRetryCount?.retryCount + 1;
    var fileName = activityId + "_" + imageName + ext;
    //adding sensor data
    sensorImageDetails.push({
      attemptCount: attemptCount,
      fileName: fileName,
      latitude: currentLatitude,
      longitude: currentLongitude,
      pose: imageName,
      success: ImageStatus,
      timestamp: new Date().getTime(),
    });
    dispatch({
      type: "SENSOR_DETAILS",
      payload: sensorImageDetails,
    });
  };

  const offlineLoderclose = () => {
    console.log(
      "IncorrectImageCount =>",
      IncorrectImageCount,
      " tempUploadImageImageCount => ",
      tempUploadImageImageCount,
      " poseDetectionFailedImageCount => ",
      poseDetectionFailedImageCount
    );
    if (
      tempUploadImageImageCount + poseDetectionFailedImageCount >=
      IncorrectImageCount
    ) {
    }
    // 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,
      },
    });

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

    await 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.update("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[0]?.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.navigate("PI");
      IncorrectImageCount = 0; // setting back to zero
    }
    clearInterval(interval);

    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={async () => {
            if (onRetryClick) {
              SetIsInternetConnected(true);
              // CALL IF ACTIVITYID IS 0 i.e. offline flow
              // so call /preinspection to create activityId.
              var vechicleData = await Database.get("PIVechicleData");
              if (
                vechicleData?.activityId == 0 ||
                vechicleData?.activityId == undefined
              ) {
                await callActivityID();
              }
              checkPoseDetection();
            }
          }}
        >
          {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,cache: 'only-if-cached' }}
                  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}>
                <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={false}
        loading={isOfflineLoading}
      />

      <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",
  },
});
