import React, { useEffect, useRef, useState } from "react";
import Database from "../../../../Components/common/Database";
import {
  StyleSheet,
  View,
  Image,
  Text,
  StatusBar,
  NativeModules,
  DeviceEventEmitter,
  PermissionsAndroid,
  BackHandler,
  Alert,
  Platform,
} from "react-native";
import {
  SCREEN_HEIGHT,
  SCREEN_WIDTH,
  image_pose_blur,
  image_pose_dark,
  image_pose_wrong,
  VIDEO_TITLE_HN,
  VIDEO_TITLE,
  RC_BOOK,
  RC_BOOK_HN,
  SELFI_IMAGE_HN,
  SELFI_IMAGE,
  get4WPoseFileNames,
  get2WPoseFileNotDoc,
  detectOnlyPoseFileNames,
  multiplePics,
  DOC,
} from "../common/Constants";
import { translate } from "react-native-digitcamera/src/common/localize/i18n";
import Orientation from "../../../react-native-orientation";
import { TouchableOpacity } from "react-native-gesture-handler";
import RNFetchBlob from "rn-fetch-blob";
import { SELFSURVEYSERVICE_DOCUMENT_URL } from "../Api/ApiUrls";
import ViewShot, { captureRef } from "react-native-view-shot";
import VideoPlayer from "react-native-video-player";
import { poseDetection } from "../common/Services/poseDetection";
import reactotron from "reactotron-react-native";
import { Spinner } from "../common/ThemedComponents";
import NetInfo from "@react-native-community/netinfo";
import DeviceInfo from "react-native-device-info";
const { getImei } = require("react-native-imei");
const iOS = Platform.OS === "ios";
import { SafeAreaView } from "react-native-safe-area-context";
// import moment from "moment";

let realm = Database.getRealm();

import {
  CHASSIS_NUMBER,
  ACTIVITY_TYPE_MOTOR_2W_PRE_INSPECTION_SELF_SURVEY,
  ACTIVITY_TYPE_MOTOR_4W_OD_NB_PRE_INSPECTION_SELF_SURVEY,
  ACTIVITY_TYPE_MOTOR_PRE_INSPECTION_SELF_SURVEY,
  ACTIVITY_TYPE_MOTOR_CVOD_PRE_INSPECTION_SELF_SURVEY,
} from "../common/Constants";
import { chassiesPoseDetetction } from "../common/Services/chassisPoseDetection";
import { useSelector, useDispatch } from "react-redux";
import { async } from "validate.js";
import Colors from "react-native-digitcamera/src/common/Colors";
import { firebaseAttributes } from "../common/libEventLog/libCrashlytics/libCrashlyticsEvent";
import {
  UELogEvent,
  UELogMessage,
  UEStartTimer,
  UEEndTimer
} from "react-native-digitcamera/src/common/libEventLog/UserExperior/LibUserExperior";
//Global variables
var AppLoginStatus = realm.objects("AppLoginStatus");
var PIclickedCount = realm.objects("PIclickedCount");
var sensorImageDetails = [];
var SensorData;
var mSensorManager = NativeModules.SensorManager;
var accelerometerData = [];
var gyroscopeData = [];
var magnetometerData = [];
var pedometerData = [];
var message;
var locationRetryCount = 0;
// location from realm
var currentLatitude, currentLongitude;
var noOfImagesGoneForPoseDection = 0,
  noOfImagesPoseDetedImages = 0;

const PreviewImage = ({ navigation, route }) => {
  var reTryDataLen = 0;
  const imageref = useRef();
  const [dateAndTime, SetDateAndTime] = useState("");
  const [imageName, SetImageName] = useState("");
  const [finalImagePath, SetFinalImagePath] = useState("");
  const [uploadState, SetUploadState] = useState("");
  const dispatch = useDispatch();
  const RetryImageData = useSelector((state) => state.RetryImageData);
  // const RetryCountData = useSelector((state) => state.RetryCountData);
  const isLastData = useSelector((state) => state.isLastData);
  const [isLoading, setISsLoading] = useState();
  const [isInternetConnected, SetIsInternetConnected] = useState(true);
  const [APILevel, SetAPILevel] = useState("");
  const [IMEI, SetIMEI] = useState("");
  const [deviceName, SetDeviceName] = useState("");
  const [MAC, SetMAC] = useState("");
  const [IP, SetIP] = useState("");
  const isCPDReceived = useRef(false) // checks is chassis pose detection data received or not

  var PIVechicleData = realm.objects("PIVechicleData");
  var PIRetryCount = realm.objects("PIRetryCount");
  var PIOdometerData = realm.objects("PIOdometerData");

  var activityId = PIVechicleData[0]?.activityId;
  var activityTypeId = PIVechicleData[0]?.activityTypeId;
  const {
    ImageData,
    ext,
    DocumentImageName,
    // activityId,
    // activityTypeId,
    webUserId,
    title,
    titleHn,
    subTitle,
    subTitleHn,
    totalSteps,
    stepStencilAssests,
    points,
    image,
    TotalImage,
    currentIndex,
    retryCount,
    licensePlateNumber,
    isLast,
  } = route.params;

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

  useEffect(() => {
    var PILocation = realm.objects("PILocation");
    currentLatitude = PILocation[0]?.lat;
    currentLongitude = PILocation[0]?.long;
    if (
      locationRetryCount < 2 &&
      (currentLatitude === undefined || currentLongitude === undefined)
    ) {
      locationRetryCount += 1;
      Alert.alert(
        "Turn Off/On Location",
        "Oops! We are not able to fetch your location details. Please try again after turning Off and then On"
      );
      return;
    }
    // getting os info
    getDeviceInfo();
    let netInfoSubscription = NetInfo.addEventListener((state) => {
      if (state.isInternetReachable) {
        SetIsInternetConnected(true);
      } else {
        SetIsInternetConnected(false);
      }
    });
    getTime();
    Orientation.lockToLandscapeLeft();
    if (Platform.OS === "android") checkStoragePermission();

    let unsubscribe = navigation.addListener("focus", () => {
      Orientation.lockToLandscapeLeft();
    });
    // disabled back handler
    const backHandler = BackHandler.addEventListener(
      "hardwareBackPress",
      () => {
        return true;
      }
    );

    return () => {
      backHandler.remove();
      unsubscribe();
      netInfoSubscription();
    };
  }, []);

  const checkStoragePermission = async () => {
    const grantedSorage = await PermissionsAndroid.request(
      PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE
    );
    UELogEvent("Granted storage ?", {
      "is granted": JSON.stringify(grantedSorage),
    });
  };
  // for gatting time
  const getTime = () => {
    const date = new Date().getDate();
    const month = new Date().getMonth() + 1;
    const year = new Date().getFullYear();

    //Time calulation for the display on preciew Screen
    const hour = new Date().getHours();
    const minute = new Date().getMinutes();
    const seconds = new Date().getSeconds();
    SetDateAndTime(
      date +
      "/" +
      month +
      "/" +
      year +
      " - " +
      hour +
      ":" +
      minute +
      ":" +
      seconds
    );
  };

  // Navigation functions
  const navigationFunc = () => {
    var PIGonePoseDetection = realm.objects("PIGonePoseDetection");
    var PIPoseDetectionCompleted = realm.objects("PIPoseDetectionCompleted");
    console.log("Retry Data from Redux");
    console.log("RETRY_DATA_LEN >>>", reTryDataLen, isLast);
    console.log(
      "noOfImagesGoneForPoseDection >>>",
      noOfImagesGoneForPoseDection,
      PIGonePoseDetection[0]?.GoneposeDetectionCount
    );
    UELogEvent("Navigation function started..", {
      noOfImagesGoneForPoseDection: JSON.stringify(
        noOfImagesGoneForPoseDection
      ),
      "PiGonePoseDetection[0].GoneposeDetectionCount": JSON.stringify(
        PIGonePoseDetection[0]?.GoneposeDetectionCount
      ),
    });


    setISsLoading(false);


    if (
      // All images captured & to be gone for pose detection
      isLast &&
      reTryDataLen == 0 &&
      isInternetConnected &&
      PIGonePoseDetection[0]?.GoneposeDetectionCount == 0
    ) {
      UELogEvent("Flow completed and image uploaded", {
        "Retry Instructions": JSON.stringify(
          RealmRetryInstructionData,
          null,
          "  "
        ),
      });
      console.log("FLOW COMPLETED AND IMAGE UPLOADED");
      realm.write(() => {
        realm.delete(realm.objects("PIOfflineData"));
        realm.create("PIOfflineData", {
          retryImageData: !!RetryImageData
            ? JSON.stringify(RetryImageData)
            : "",
        });
      });
      var RealmRetryInstructionData = realm.objects("PIOfflineData");
      firebaseAttributes(
        "Retry Instruction",
        JSON.stringify(RealmRetryInstructionData, null, "  ")
      );
      Orientation.lockToPortrait();
      navigation.navigate("Progress", {
        TotalImage: PIclickedCount[0]?.clickedCount,
      });
    } else {
      // some images gone for pose detection
      if (PIGonePoseDetection[0]?.GoneposeDetectionCount > 0 && isLast && reTryDataLen != 0) {
        // if images are gone for pose but still not get single failed responce
        navigation.navigate("InvalidImages", {
          isLast: isLast,
        });
        UELogEvent(
          "// if images are gone for pose but still not get single failed responce...",
          {
            isLast: isLast,
            "Retry Data Length": reTryDataLen,
          }
        );
      } else {
        //
        if (isLast && reTryDataLen != 0) {
          UELogEvent("else if block (isLast && retrydatalen !=0)", {
            isLast: JSON.stringify(isLast),
            reTryDataLen: JSON.stringify(reTryDataLen),
          });
          realm.write(() => {
            realm.delete(realm.objects("PIOfflineData"));
            realm.create("PIOfflineData", {
              retryImageData: !!RetryImageData
                ? JSON.stringify(RetryImageData)
                : "",
            });
          });
          navigation.navigate("InvalidImages", {
            isLast: isLast,
          });
        } else {
          // console.log('IMAGE PENDING TO CAPTURE > ');
          UELogEvent("Image pending to capture..");
          if (title == RC_BOOK || titleHn == RC_BOOK_HN) {
            navigation.navigate("PI", { photo: "", isRCBook: true });
          } else if (isLast) {
            navigation.navigate("Progress", {
              TotalImage: PIclickedCount[0]?.clickedCount,
            });
          } else {

            /*
            @CHASSIS
            
            In UAT Chassis Pose Detection API has slight delay in response around 6-8 sec
            until response is received, user should not proceed further otherwise
            Chassis Image wont upload in some cases.

            if CHASSIS_NUMBER and for 2w and For First Take only this should apply.

            */

            if (DocumentImageName === CHASSIS_NUMBER && activityTypeId === 26 && PIRetryCount[0]?.retryCount == 0) {
              console.log("^^^ PREVIEWIMAGE, checking cpd response");
              const CPDResponseCheckInterval = setInterval(() => {
                if (isCPDReceived.current) {
                  setISsLoading(false);
                  console.log("^^^ PREVIEWIMAGE, cpd response recieved");
                  navigation.navigate("PI");
                  clearInterval(CPDResponseCheckInterval)
                }
              }, 1000)
            }
            else {
              navigation.navigate("PI");
            }
            // navigation.navigate("Progress", { // This step is exceptional, we are directly uploading whatever images available
            //   TotalImage: PIclickedCount[0]?.clickedCount,
            // });
          }
        }
      }
    }
  };

  //CALL CHASSIS POSE DETECTION
  const callChassisPoseDetection = async (uri) => {
    UELogEvent("callChassisPoseDetection started..", {
      uri: JSON.stringify(uri),
    });
    console.log("URI >>>> ", uri);
    var formdata = new FormData();
    formdata.append("file", {
      uri: uri,
      name: activityId + "_" + DocumentImageName + ext,
      fileName: activityId + "_" + DocumentImageName,
      type: "image/jpeg",
    });
    formdata.append("activityId", activityId);

    var PIGonePoseDetection = realm.objects("PIGonePoseDetection");
    noOfImagesGoneForPoseDection =
      PIGonePoseDetection[0].GoneposeDetectionCount + 1;
    realm.write(() => {
      realm.delete(realm.objects("PIGonePoseDetection"));
      realm.create("PIGonePoseDetection", {
        GoneposeDetectionCount: noOfImagesGoneForPoseDection,
      });
    });
    UELogEvent("gathered data in callChassisPoseDetection", {
      formdata: JSON.stringify(formdata),
      PIGonePoseDetection: JSON.stringify(PIGonePoseDetection),
    });

    UELogEvent("calling chassisPoseDetection api", {
      body: JSON.stringify(formdata),
    });

    setISsLoading(true)


    let ChassisPoseDetectionData;
    try {
      ChassisPoseDetectionData = await chassiesPoseDetetction({
        body: formdata,
      })
      console.log("*** PREVIEWIMAGE, ChassisPoseDetectionData, isCPDRecieved before in try", isCPDReceived.current)
      isCPDReceived.current = true;
      console.log("*** PREVIEWIMAGE, ChassisPoseDetectionData, isCPDRecieved after in try", isCPDReceived.current)
    }
    catch (e) {
      console.log("*** PREVIEWIMAGE, ChassisPoseDetectionData, isCPDRecieved before in catch", isCPDReceived.current)
      isCPDReceived.current = true;
      console.log("*** PREVIEWIMAGE, ChassisPoseDetectionData, isCPDRecieved after in catch", isCPDReceived.current)
      console.log("***PreviewImage, error in chassiesPoseDetection =>", e);
    }

    var PIPoseDetectionCompleted = realm.objects("PIPoseDetectionCompleted");
    noOfImagesPoseDetedImages =
      PIPoseDetectionCompleted[0]?.poseDetectionCompletedCount + 1;
    console.log(")))))))))))))))))))))))", noOfImagesPoseDetedImages);
    realm.write(() => {
      realm.delete(realm.objects("PIPoseDetectionCompleted"));
      realm.create("PIPoseDetectionCompleted", {
        poseDetectionCompletedCount: noOfImagesPoseDetedImages,
      });
    });

    if (
      ChassisPoseDetectionData?.match_ratio >
      ChassisPoseDetectionData?.threshold_match_ratio
    ) {
      UELogEvent("ChassisPoseDetection match ration greater than threshold", {
        "Chassis Pose Detection Match Ration": JSON.stringify(
          ChassisPoseDetectionData?.match_ratio
        ),
        "Chassis Pose Detection Match Threshold": JSON.stringify(
          ChassisPoseDetectionData?.threshold_match_ratio
        ),
      });

      UELogEvent("Upload Image uri in callChassisPoseDetection", {
        uri: JSON.stringify(uri),
      });
      uploadImage(uri);
      dispatch({
        type: "REMOVE_BY_TITLE",
        payload: title,
      });

      UELogEvent("Sensor Image Details in callChassisPoseDetection", {
        sensorImageDetails: JSON.stringify(sensorImageDetails),
      });
    } else {
      if (PIRetryCount[0]?.retryCount > 0) {
        //upload and navigate to thank you screen
        UELogEvent("upload and navigate to thank you screen", {
          "Retry count": JSON.stringify(PIRetryCount[0]?.retryCount),
        });
        uploadImage(uri);
        UELogEvent("adding sensor data in else if block", {
          sensorImageDetails: JSON.stringify(sensorImageDetails),
        });

        dispatch({
          type: "REMOVE_BY_TITLE",
          payload: title,
        });

        if (isLast) {
          UELogEvent("started executing navigationFunc() in else if if", {
            isLast: JSON.stringify(isLast),
          });
          navigationFunc();
        }
      } else {
        //adding sensor data
        addSensorImageData(".jpg", false);

        UELogEvent("adding sensor data in else else block", {
          sensorImageDetails: JSON.stringify(sensorImageDetails),
        });

        //add data to redux
        saveRetryDataInRedux(uri);

        if (isLast) {
          UELogEvent("started executing navigationFunc() in else if if", {
            isLast: JSON.stringify(isLast),
          });
          navigationFunc();
        }
      }
    }
  };

  const addSensorImageData = (ext, ImageStatus) => {
    var attemptCount = PIRetryCount[0]?.retryCount + 1;
    var fileName = activityId + "_" + DocumentImageName + ext;
    //adding sensor data
    sensorImageDetails.push({
      attemptCount: attemptCount,
      fileName: fileName,
      latitude: currentLatitude,
      longitude: currentLongitude,
      pose: DocumentImageName,
      success: ImageStatus,
      timestamp: new Date().getTime(),
    });
    dispatch({
      type: "SENSOR_DETAILS",
      payload: sensorImageDetails,
    });
  };
  // POSE DETECTION API CALL
  const callPoseDetection = async (uri) => {
    UELogEvent("callPoseDetection api call started", {
      uri: JSON.stringify(uri),
    });
    let isBlur = true,
      isDark = true;
    let imgPose;
    let poseName;
    let isDetect;

    var PIGonePoseDetection = realm.objects("PIGonePoseDetection");
    noOfImagesGoneForPoseDection =
      PIGonePoseDetection[0].GoneposeDetectionCount + 1;
    realm.write(() => {
      realm.delete(realm.objects("PIGonePoseDetection"));
      realm.create("PIGonePoseDetection", {
        GoneposeDetectionCount: noOfImagesGoneForPoseDection,
      });
    });

    console.log("Gone For Pose Detect   >>>", noOfImagesGoneForPoseDection);

    var formdata = new FormData();
    formdata.append("file", {
      uri: uri,
      name: activityId + "_" + DocumentImageName + ext,
      fileName: activityId + "_" + DocumentImageName,
      type: "image/jpeg",
    }),
      formdata.append("policyNumber", licensePlateNumber),
      formdata.append("activityTypeId", activityTypeId),
      formdata.append("checkQuality", true),
      formdata.append("source", "DIGITEDGE");

    UELogEvent("sending data to poseDetection api", {
      formdata: JSON.stringify(formdata),
      PIGonePoseDetection: JSON.stringify(PIGonePoseDetection),
    });

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

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

    var PIPoseDetectionCompleted = realm.objects("PIPoseDetectionCompleted");
    noOfImagesPoseDetedImages =
      PIPoseDetectionCompleted[0]?.poseDetectionCompletedCount + 1;
    console.log(")))))))))))))))))))))))", noOfImagesPoseDetedImages);
    realm.write(() => {
      realm.delete(realm.objects("PIPoseDetectionCompleted"));
      realm.create("PIPoseDetectionCompleted", {
        poseDetectionCompletedCount: noOfImagesPoseDetedImages,
      });
    });

    UELogEvent("Pose detect completed", {
      PIPoseDetectionCompleted: JSON.stringify(PIPoseDetectionCompleted),
    });
    console.log("Pose detect completed   >>>", noOfImagesPoseDetedImages);

    console.log(
      "POSE RESPONCE >> ",
      JSON.stringify(poseDetectionData, null, "  ")
    );

    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) {
      UELogMessage("image is type of document like RC/DL", {
        imgPose: JSON.stringify(imgPose),
        DOC: JSON.stringify(DOC),
        poseNameNotDoc: JSON.stringify(poseNameNotDoc),
      });
      var isIncorrect = false;
      var poseNameNotDoc = get2WPoseFileNotDoc(); // gating Doc
      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
      uploadImage(uri);
      UELogMessage("Upload image uri", {
        uri: JSON.stringify(uri),
      });
      //create sensor data ==> if image is uploaded
      console.log("IN if");
      UELogEvent("User Experior IN if", {
        sensorImageDetails: JSON.stringify(sensorImageDetails),
      });
    } else {
      //create sensor data ==> if image not  uploaded
      UELogMessage("create sensor data ==> if image not  uploaded");
      console.log(
        "EEEEEEEEEEEEEEEEEEEEEEE",
        activityId + "_" + DocumentImageName + ".jpg"
      );
      UELogEvent("User Experior IN else", {
        sensorImageDetails: JSON.stringify(sensorImageDetails),
      });
      // GO FOR RE-TRY
      //save the details to redux
      if (PIRetryCount[0]?.retryCount > 0) {
        // upload image without pose detection
        UELogEvent("Uploading image without pose detection", {
          "Retry Count": JSON.stringify(PIRetryCount[0]?.retryCount),
        });
        uploadImage(uri);
      } else {
        // try two time to upload image
        UELogEvent("Trying to upload two time", { uri: JSON.stringify(uri) });
        saveRetryDataInRedux(uri);
        if (isLast) {
          navigationFunc();
        }
      }
    }
  };

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

  //upload images
  const uploadImage = (uri) => {
    try {
      var ext = DocumentImageName == "VDO" ? ".mp4" : ".jpg";
      console.log("*** PreviewImage uploadImage uri: ", uri);

      /*
      * Logging file size of each media in user experior
      */

      const getFileSize = async (uri, imageName) => {
        /* 
          * Using RNFetchBlob.fs.stat(uri) method which retrieves meta information 
          * of the file of the *uri*
          * stats.size returns size of the file in bytes
          * the method, getFileSizeInMB converts the bytes into MB
        */
        try {
          const stats = await RNFetchBlob.fs.stat(uri);
          console.log(`PreviewImage.js ${imageName} file size: `, stats?.size, `bytes, ${getFileSizeInMB(stats?.size)} mb`);
          UELogEvent(`PreviewImage.js ${imageName} file size in bytes`, {
            "FileSize (bytes)": JSON.stringify(stats?.size),
            "FileSize (MegaBytes)": JSON.stringify(getFileSizeInMB(stats?.size))
          })
        }
        catch (e) {
          console.log("Error in PreviewImage.js uploadImage, getFileSize", e);
        }
      }

      const getFileSizeInMB = (bytes) => {
        /* converts bytes to megabytes */
        return bytes * 0.000001;
      }

      // Calling getFileSize
      getFileSize(uri, DocumentImageName)


      UELogEvent("uploadImage is started", {
        uri: JSON.stringify(uri),
        documentName: JSON.stringify(DocumentImageName),
        ImageName: JSON.stringify(activityId + "_" + DocumentImageName + ext),
      });
      console.log("In Upload Uploading Image Name ", DocumentImageName);
      console.log("IMAGE NAME  ", activityId + "_" + DocumentImageName + ext);
      const xhr = new XMLHttpRequest();
      const formData = new FormData();
      console.log("IMAGE URI TO BE UPLOADED > > >   ", uri);
      const handleProgress = (event) => {
        UEStartTimer(SELFSURVEYSERVICE_DOCUMENT_URL)

        // UELogEvent("handleProgress started", {
        //   "File Uploaded": JSON.stringify(
        //     Math.round(event.loaded * 100) / event.total
        //   ),
        // });
        console.log(
          "File Uploaded => ",
          Math.round(event.loaded * 100) / event.total
        );
      };
      UELogEvent("IN UPLOAD => DOCUMENT STATUS ==> isLast", {
        isLast: JSON.stringify(isLast),
      });
      console.log(
        "IN UPLOAD => DOCUMENT STATUS ==> isLast = ",
        isLast.toString()
      );
      console.log("*** PreviewImage uploadImage preparing payload: ");
      const documentUploadData = {
        activityId: activityId,
        data: null,
        dataUploadStatus: 0,
        fullName: activityId + "_" + DocumentImageName,
        geoLocation: {
          isBlocked: "",
          deviceName: deviceName,
          latitude: currentLatitude,
          longitude: currentLongitude,
          operatingSystem: DeviceInfo.getSystemVersion(),
          timezone: "Asia/Kolkata",
          deviceTime: null,
          ipAddress: IP,
          deviceIMEI: IMEI[0],
          macAddress: MAC,
          documentSource: "DigitEdge",
        },
        isLast: "false",
        isLastData: "false",
        isLastDocument: "false",
        isSurveyor: "false",
        manualOdometerReading:
          DocumentImageName == "ODO" ? PIOdometerData[0]?.readings : "",
        source: "DIGITEDGE",
      };
      console.log(
        "*** PreviewImage uploadImage payload ready: ",
        JSON.stringify(documentUploadData)
      );

      formData.append("file", {
        uri: uri,
        type: "image/jpeg",
        fileName: activityId + "_" + DocumentImageName,
        name: activityId + "_" + DocumentImageName + ext,
      });
      formData.append("documentData", JSON.stringify(documentUploadData));
      console.log(
        "*** PreviewImage uploadImage fileName: " +
        activityId +
        "_" +
        DocumentImageName +
        " name:" +
        activityId +
        "_" +
        DocumentImageName +
        ext
      );

      UELogEvent("started xhr events in uploadImage", {
        formdata: JSON.stringify(formData),
      });

      xhr.upload.addEventListener("progress", handleProgress);
      xhr.addEventListener("load", () => {
        UEEndTimer(SELFSURVEYSERVICE_DOCUMENT_URL)
        UELogEvent("in xhr load", {
          "status": JSON.stringify(xhr.status),
          "response": JSON.stringify(xhr.response)
        });
        //adding sensor data
        addSensorImageData(ext, true);

        var PIUploadedCount = realm.objects("PIUploadedCount");
        var uploadedImageCount = PIUploadedCount[0]?.uploadedCount;
        console.log("Uploaded", DocumentImageName);
        uploadedImageCount = uploadedImageCount + 1;
        console.log("HOW MANY IMAGES UPLOADED => ", uploadedImageCount);
        UELogMessage(`Uploaded ${DocumentImageName}`, {
          "uploaded images": JSON.stringify(uploadedImageCount),
        });

        firebaseAttributes(
          activityId + "_" + DocumentImageName + ext + "\n" + documentUploadData
        );
        realm.write(() => {
          realm.delete(realm.objects("PIUploadedCount"));
          realm.create("PIUploadedCount", {
            uploadedCount: uploadedImageCount,
          });
        });
        console.log("UPLOADED COUNT >>> ", uploadedImageCount);
      });

      xhr.addEventListener("abort", () => {
        UEEndTimer(SELFSURVEYSERVICE_DOCUMENT_URL)

        addSensorImageData(ext, false);

        UELogMessage("xhr event abort in uploadImage", {
          uri: JSON.stringify(uri),
          "status": JSON.stringify(xhr.status)
        });
        saveRetryDataInRedux(uri);
        console.log("abort");
      });
      xhr.addEventListener("error", () => {
        UEEndTimer(SELFSURVEYSERVICE_DOCUMENT_URL)

        addSensorImageData(ext, false);

        UELogMessage("xhr event error in uploadImage", {
          uri: JSON.stringify(uri),
          "status": JSON.stringify(xhr.status)
        });
        saveRetryDataInRedux(uri);
        console.log("error");
      });
      xhr.addEventListener("timeout", () => {
        UEEndTimer(SELFSURVEYSERVICE_DOCUMENT_URL)

        addSensorImageData(ext, false);

        UELogMessage("xhr event timeout in uploadImage", {
          uri: JSON.stringify(uri),
          "status": JSON.stringify(xhr.status)
        });

        saveRetryDataInRedux(uri);
        console.log("timeout");
      });
      xhr.open("POST", SELFSURVEYSERVICE_DOCUMENT_URL);
      xhr.setRequestHeader(
        "Accept",
        "*/*",
        "Content-Type",
        "multipart/form-data"
      );
      xhr.send(formData);
      console.log(
        "*** PreviewImage uploadImage request sent to : " +
        SELFSURVEYSERVICE_DOCUMENT_URL
      );

      if (isLast) {
        UELogEvent("started navigationFunc() in upload image");
        navigationFunc();
      }
    } catch (error) {
      console.log("*** PreviewImage uploadImage catch: ", error);
    }
  };

  // create image with info
  const createImageWithName = async () => {
    if (title == VIDEO_TITLE || titleHn == VIDEO_TITLE_HN) {
      if (isInternetConnected) {
        UELogMessage("Creating Video", {
          title: VIDEO_TITLE,
          titleHindi: VIDEO_TITLE_HN,
          imageData: ImageData,
        });
        uploadImage(ImageData);
      } else {
        UELogMessage("Not connected to internet while creating video", {
          title: VIDEO_TITLE,
          titleHindi: VIDEO_TITLE_HN,
          imageData: ImageData,
        });
        saveRetryDataInRedux(ImageData);
        Alert.alert("Please check your internet connection !!!");
      }
      setISsLoading(false);
    } else {
      UELogEvent("creating image with name");
      try {
        UELogEvent("Inside try block of create image", {
          imageRef: "imageref",
        });
        await captureRef(imageref, {
          format: "jpg",
          quality: 0.8,
        }).then(
          (uri) => {
            setISsLoading(false);
            UELogEvent("inside captureRef then,", {
              Data: JSON.stringify({
                CHASSIS_NUMBER,
                ACTIVITY_TYPE_MOTOR_PRE_INSPECTION_SELF_SURVEY,
                activityTypeId,
                "activityTypeId===activityTypeMotorPreInspectionSelfSurvey":
                  activityTypeId ===
                  ACTIVITY_TYPE_MOTOR_PRE_INSPECTION_SELF_SURVEY,
                "typeof ACTIVITY_TYPE_MOTOR_PRE_INSPECTION_SELF_SURVEY":
                  typeof ACTIVITY_TYPE_MOTOR_PRE_INSPECTION_SELF_SURVEY,
                "typeof activityTypeId": typeof activityTypeId,
              }),
            });
            console.log(
              "QQQQQQQQQQQQ",
              CHASSIS_NUMBER,
              ACTIVITY_TYPE_MOTOR_PRE_INSPECTION_SELF_SURVEY,
              activityTypeId,
              activityTypeId == ACTIVITY_TYPE_MOTOR_PRE_INSPECTION_SELF_SURVEY,
              typeof ACTIVITY_TYPE_MOTOR_PRE_INSPECTION_SELF_SURVEY,
              typeof activityTypeId
            );
            UELogMessage("Setting Final Image Path", {
              uri: uri,
            });
            SetFinalImagePath(uri);
            if (
              title == SELFI_IMAGE ||
              titleHn == SELFI_IMAGE_HN ||
              activityTypeId ==
              ACTIVITY_TYPE_MOTOR_CVOD_PRE_INSPECTION_SELF_SURVEY || // for CV
              AppLoginStatus[0]?.userType == "OEMDealer" ||
              DocumentImageName == "SF" ||
              DocumentImageName == "CNG" ||
              DocumentImageName == "IWS" ||
              PIRetryCount[0]?.retryCount > 0
              || DocumentImageName.includes("RCB") || DocumentImageName == "PUC"
            ) {
              UELogEvent("inside if ", {
                data: JSON.stringify({
                  title: SELFI_IMAGE,
                  titleHn: SELFI_IMAGE_HN,
                  "activityTypeId is activity type motor cvod PI Self survey":
                    activityTypeId ==
                    ACTIVITY_TYPE_MOTOR_CVOD_PRE_INSPECTION_SELF_SURVEY,
                  UserType: AppLoginStatus[0]?.userType,
                  DocumentImageName: DocumentImageName,
                }),
              });
              if (isInternetConnected) {
                UELogEvent("internet connected  while creating image", {
                  uri: uri,
                });
                console.log(
                  "addSensorImageData SF/30/ OEMDealer/CNG/IWS:  : true"
                );
                uploadImage(uri);
              } else {
                UELogEvent("no interent connected while creating image", {
                  uri: uri,
                });
                saveRetryDataInRedux(uri);
                Alert.alert("Please check your internet connection !!!");
              }
              reactotron.log("IN SELFI");
            } else {
              if (DocumentImageName === CHASSIS_NUMBER) {
                // call API for chassies number pose detection
                UELogEvent("call API for chassies number pose detection", {
                  DocumentImageName: DocumentImageName,
                });
                if (isInternetConnected) {
                  UELogEvent(
                    "internet connected while calling callChassisPoseDetection",
                    {
                      uri: uri,
                    }
                  );
                  callChassisPoseDetection(uri);
                } else {
                  UELogEvent(
                    "internet not connected while calling callChassisPoseDetection",
                    {
                      uri: uri,
                    }
                  );
                  saveRetryDataInRedux(uri);
                  Alert.alert("Please check your internet connection !!!");
                }
              } else if (
                activityTypeId ==
                ACTIVITY_TYPE_MOTOR_2W_PRE_INSPECTION_SELF_SURVEY // for 2W
              ) {
                UELogEvent("called from 2W Image Creation", {
                  uri: uri,
                });
                console.log("called from 2W Image Creation");
                // call APi for pose detection for 2W
                if (isInternetConnected) {
                  UELogEvent(
                    "Internet connected while calling callPoseDetection 2w",
                    {
                      uri: uri,
                    }
                  );
                  callPoseDetection(uri);
                } else {
                  UELogEvent(
                    "internet not connected while calling callPoseDetection 2w",
                    {
                      uri: uri,
                    }
                  );
                  saveRetryDataInRedux(uri);
                  Alert.alert("Please check your internet connection !!!");
                }
              } else if (
                activityTypeId ==
                ACTIVITY_TYPE_MOTOR_PRE_INSPECTION_SELF_SURVEY ||
                activityTypeId == "5" ||
                activityTypeId ==
                ACTIVITY_TYPE_MOTOR_4W_OD_NB_PRE_INSPECTION_SELF_SURVEY
              ) {
                // call API for 4W pose detection
                UELogEvent("call API for 4W pose detection", {
                  uri: uri,
                });
                if (isInternetConnected) {
                  UELogEvent(
                    "internet not connected while calling callPoseDetection 4w",
                    {
                      uri: uri,
                    }
                  );
                  callPoseDetection(uri);
                } else {
                  UELogEvent(
                    "internet not connected while calling callPoseDetection 4w",
                    {
                      uri: uri,
                    }
                  );
                  saveRetryDataInRedux(uri);
                  Alert.alert("Please check your internet connection !!!");
                }
              }
            }
          },

          (error) => {
            setISsLoading(false);
            UELogEvent("caught error while creating image", {
              Error: JSON.stringify(error),
            });
          }
        );
      } catch (err) {
        setISsLoading(false);
        UELogEvent("caught error in catch block of capture ref", {
          Error: JSON.stringify(err),
        });
        console.log("Error in view shot", err);
      }
    }
  };

  const saveRetryDataInRedux = (uri) => {
    UELogEvent("saveRetryDataInRedux", {
      uri: uri,
    });
    console.log("URI in saveRetryDataInRedux() =>", uri);
    //add data to redux
    dispatch({
      type: "RETRY_IMAGES",
      payload: {
        retryImageInfo: {
          imageName: DocumentImageName,
          imagePath: uri,
          fileNameWithExt: activityId + "_" + DocumentImageName + ext,
          fileName: activityId + "_" + DocumentImageName,
          title: title,
          subTitle: subTitle,
          titleHn: titleHn,
          subTitleHn: subTitleHn,
          msg: message,
          stepStencilAssests,
          points,
          image,
          uploaded: false,
        },
      },
    });
    if (isLast) {
      UELogEvent("starting to run navigationFunc()", {
        isLast: isLast,
      });
      navigationFunc();
    }

    UELogEvent("Redux data,retry image data", {
      RetryImageData: JSON.stringify(RetryImageData),
    });
    firebaseAttributes(
      "REDUX DATA : " + JSON.stringify(RetryImageData, null, "  ")
    );

    // let tempArray = RetryImageData;
    // tempArray.retryImageInfo.push({
    //   imageName: DocumentImageName,
    //   imagePath: uri,
    //   fileNameWithExt: activityId + '_' + DocumentImageName + ext,
    //   fileName: activityId + '_' + DocumentImageName,
    //   title: title,
    //   subTitle: subTitle,
    //   titleHn: titleHn,
    //   subTitleHn: subTitleHn,
    //   msg: message,
    //   stepStencilAssests,
    //   points,
    //   image,
    //   uploaded: false,
    // });
    // console.log('111111111111111111', tempArray);
    // if (isLast) {
    //   navigationFunc(tempArray);
    // }
    // tempArray = {};
  };

  // retry redux length
  const callRetrayDataCount = () => {
    reTryDataLen = RetryImageData?.retryImageInfo?.length;
    UELogEvent("callRetrayDataCount started", {
      "retry data length": reTryDataLen,
    });
    console.log("REDUX LEN >", reTryDataLen);
  };
  return (
    <SafeAreaView
      edges={iOS ? ["top", "bottom", "right"] : []}
      style={styles.safeArea}
    >
      <View style={styles.main}>
        <Spinner loading={isLoading} />
        {callRetrayDataCount()}
        <StatusBar hidden={true} />
        {/* Image View */}
        <View style={styles.imageView}>
          {/* Image */}
          {title == VIDEO_TITLE || title == VIDEO_TITLE_HN ? (
            <VideoPlayer
              video={{ uri: ImageData }}
              pauseOnPress={true}
              autoplay={true}
              disableSeek={true}
            // style={styles.productImageStyle}
            ></VideoPlayer>
          ) : (
            <ViewShot ref={imageref}>
              <View>
                <Image
                  source={{ uri: ImageData.uri }}
                  style={{
                    width: "100%",
                    height: "100%",
                    resizeMode: "cover",
                    // alignSelf: "center",
                  }}
                />
                {/* info Strip */}
                <View style={styles.infoTextView}>
                  <Text style={styles.infoText}>
                    {translate("Lat:") +
                      " " +
                      currentLatitude +
                      "  " +
                      translate("Lon:") +
                      "  " +
                      currentLongitude +
                      "  " +
                      "    |    " +
                      "Digit App" +
                      "    |    " +
                      dateAndTime}
                  </Text>
                </View>
              </View>
            </ViewShot>
          )}
        </View>
        {/* Button View */}
        <View style={styles.buttonView}>
          {/* Retake View */}
          <View style={styles.retakeView}>
            <TouchableOpacity
              onPress={() => {
                navigation.navigate("Camera");
              }}
            >
              <Image
                source={retake}
                style={{ width: 18, height: 18, alignSelf: "center" }}
              />
              <Text style={styles.retakeText}>{translate("Retake")}</Text>
            </TouchableOpacity>
          </View>
          {/* Proceed View */}
          <View style={styles.proceedView}>
            <TouchableOpacity
              onPress={() => {
                console.log(
                  ">>>>>>>>>>>>",
                  AppLoginStatus[0]?.userType,
                  AppLoginStatus[0]?.userType == "OEMDealer"
                );
                console.log(
                  "PIRetryCount[0]?.retryCount   >>> >> > ",
                  PIRetryCount[0]?.retryCount
                );
                if (PIRetryCount[0]?.retryCount == 0) {
                  var ImageClickedCount = PIclickedCount[0]?.clickedCount;
                  ImageClickedCount = ImageClickedCount + 1;
                  // dispatch({
                  //   type: 'IMAGE_CLICKED_COUNT',
                  //   payload: {
                  //       ImageClickedCount: ImageClickedCount,
                  //     },
                  // });

                  realm.write(() => {
                    realm.delete(realm.objects("PIclickedCount"));
                    realm.create("PIclickedCount", {
                      clickedCount: ImageClickedCount,
                    });
                  });

                  console.log(
                    "Click COUNT >>> ",
                    PIclickedCount[0]?.clickedCount
                  );
                }
                // if (DocumentImageName !== CHASSIS_NUMBER) {
                //   setISsLoading(true);
                // }
                setISsLoading(true);
                createImageWithName();
                if (!isLast) {
                  navigationFunc();
                }
                // else if (title == SELFI_IMAGE || titleHn == SELFI_IMAGE_HN || activityTypeId == ACTIVITY_TYPE_MOTOR_CVOD_PRE_INSPECTION_SELF_SURVEY) {
                //   navigationFunc();
                // }
              }}
            >
              <Image
                source={proceed}
                style={{ width: 49, height: 49, alignSelf: "center" }}
              />
              <Text style={styles.retakeText}>{translate("Proceed")}</Text>
            </TouchableOpacity>
          </View>
          {/* Blank View */}
          <View style={styles.blankView}></View>
        </View>
      </View>
    </SafeAreaView>
  );
};
export default PreviewImage;

const styles = StyleSheet.create({
  safeArea: {
    flex: 1,
    backgroundColor: Colors.darkBlack,
  },
  main: {
    flex: 1,
    flexDirection: "row",
  },
  buttonView: {
    flex: 0.1,
    backgroundColor: "#000000",
  },
  imageView: {
    flex: 0.9,
    alignSelf: "center",
  },
  retakeView: {
    flex: 0.333333,
    justifyContent: "center",
  },
  proceedView: {
    flex: 0.333333,
    justifyContent: "center",
  },
  blankView: {
    flex: 0.3333333,
  },
  retakeText: {
    fontFamily: "Muli-Regular",
    fontSize: 11,
    alignSelf: "center",
    marginTop: 5,
    color: "#FFFFFF",
  },
  infoTextView: {
    // flex:0.1,
    position: "absolute",
    width: SCREEN_HEIGHT,
    height: 48,
    backgroundColor: "#000000",
    opacity: 0.58,
    justifyContent: "center",
  },
  infoText: {
    fontFamily: "Muli-SemiBold",
    fontSize: 14,
    color: "#FFFFFF",
    marginLeft: 24,
    marginRight: 24,
  },
});
