import React, { useEffect, useMemo, useRef, useState } from "react";
import Database from "../../../../Components/common/DAsyncStorage";
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,
  canGoVideoPi,
  is2Wflow,
  isCVFlow,
} 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";
const maxSize = Math.max(SCREEN_HEIGHT, SCREEN_WIDTH);
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 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";
import {
  DTLogError,
  DTLogEvent,
} from "react-native-digitcamera/src/common/libEventLog/Dynatrace/LibDynatrace";
import {
  getCurrentActivity,
  offlinePIDataToRealm,
  updateActivityStatus,
} from "react-native-digitcamera/src/Screens/OfflineFlow/CommonFunc";
import { CreateActivityId } from "react-native-digitcamera/src/Screens/OfflineFlow/CreateActivityId";

import debounce from "lodash.debounce";
import { BackgroundUploadFile2W } from "react-native-digitcamera/src/Screens/SilentUpload/SilentUploadUtils";
import { initMediaFile } from "react-native-digitcamera/src/Screens/SilentUploadV2/DatabaseHelpers";
const DEBOUNCE_INTERVAL = 500;
//Global variables
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;

let make = "";
let model = "";

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, setISLoading] = useState();
  const [isInternetConnected, SetIsInternetConnected] = useState(false);
  const [APILevel, SetAPILevel] = useState("");
  const [IMEI, SetIMEI] = useState("");
  const [deviceName, SetDeviceName] = useState("");
  const [MAC, SetMAC] = useState("");
  const [IP, SetIP] = useState("");
  const [currentLatitude, setCurrentLatitude] = useState("NA");
  const [currentLongitude, setCurrentLongitude] = useState("NA");
  const isCPDReceived = useRef(false); // checks is chassis pose detection data received or not

  const network = useSelector((state) => state.network);
  const { isInternetReachable } = network;

  useEffect(() => {
    if (isInternetReachable === true) {
      SetIsInternetConnected(true);
    } else if (isInternetReachable === false) {
      SetIsInternetConnected(false);
    }
  }, [network]);

  // var activityTypeId = PIVechicleData?.activityTypeId;
  const {
    uri,
    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(() => {
    const checkLocation = async () => {
      var PILocation = await Database.get("PILocation");
      const lat = PILocation?.lat;
      const long = PILocation?.long;
      if (lat && long) {
        setCurrentLatitude(lat);
        setCurrentLongitude(long);
      }
    };
    checkLocation();
    // getting os info
    getDeviceInfo();

    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();
    };
  }, []);

  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 = async () => {
    var PIRetryCount = await Database.get("PIRetryCount");
    var PIclickedCount = await Database.get("PIclickedCount");
    var PIGonePoseDetection = await Database.get("PIGonePoseDetection");
    var PIPoseDetectionCompleted = await Database.get(
      "PIPoseDetectionCompleted"
    );
    console.log("Retry Data from Redux");
    console.log("RETRY_DATA_LEN >>>", reTryDataLen, isLast);
    console.log(
      "noOfImagesGoneForPoseDection >>>",
      noOfImagesGoneForPoseDection,
      PIGonePoseDetection?.GoneposeDetectionCount
    );
    UELogEvent("Navigation function started..", {
      noOfImagesGoneForPoseDection: JSON.stringify(
        noOfImagesGoneForPoseDection
      ),
      "PIGonePoseDetection.GoneposeDetectionCount": JSON.stringify(
        PIGonePoseDetection?.GoneposeDetectionCount
      ),
    });

    setISLoading(false);

    if (
      // All images captured & to be gone for pose detection
      isLast &&
      reTryDataLen == 0 &&
      isInternetReachable &&
      PIGonePoseDetection?.GoneposeDetectionCount == 0
    ) {
      UELogEvent("Flow completed and image uploaded", {
        "Retry Instructions": JSON.stringify(
          RealmRetryInstructionData,
          null,
          "  "
        ),
      });
      console.log("FLOW COMPLETED AND IMAGE UPLOADED");
      await Database.update("PIOfflineData", {
        retryImageData: !!RetryImageData ? JSON.stringify(RetryImageData) : "",
      });
      var RealmRetryInstructionData = await Database.get("PIOfflineData");
      firebaseAttributes(
        "Retry Instruction",
        JSON.stringify(RealmRetryInstructionData, null, "  ")
      );
      if (isInternetReachable) {
        Orientation.lockToPortrait();
        var activity = await getCurrentActivity();
        await updateActivityStatus("IN-PROGRESS", activity);
        navigation.navigate("ActivityScreen");
      } else {
        navigation.navigate("InvalidImages", {
          isLast: isLast,
        });
      }
    } else {
      // some images gone for pose detection
      if (
        PIGonePoseDetection?.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),
          });
          await Database.update("PIOfflineData", {
            retryImageData: !!RetryImageData
              ? JSON.stringify(RetryImageData)
              : "",
          });
          if (isCVFlow(activityTypeId)) {
            Orientation.lockToPortrait();
            var activity = await getCurrentActivity();
            await updateActivityStatus("IN-PROGRESS", activity);
            navigation.navigate("ActivityScreen");
          } else {
            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) {
            if (isCVFlow(activityTypeId)) {
              Orientation.lockToPortrait();
              var activity = await getCurrentActivity();
              await updateActivityStatus("IN-PROGRESS", activity);
              navigation.navigate("ActivityScreen");
            } else {
              if (isInternetReachable) {
                Orientation.lockToPortrait();
                var activity = await getCurrentActivity();
                await updateActivityStatus("IN-PROGRESS", activity);
                navigation.navigate("ActivityScreen");
              } else {
                navigation.navigate("InvalidImages", {
                  isLast: isLast,
                });
              }
            }
          } 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 &&
              is2Wflow(activityTypeId) &&
              PIRetryCount?.retryCount == 0 &&
              isInternetReachable
            ) {
              console.log("^^^ PREVIEWIMAGE, checking cpd response");
              const CPDResponseCheckInterval = setInterval(() => {
                if (isCPDReceived.current) {
                  setISLoading(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?.clickedCount,
            // });
          }
        }
      }
    }
  };

  //CALL CHASSIS POSE DETECTION
  const callChassisPoseDetection = async (uri) => {
    var PIRetryCount = await Database.get("PIRetryCount");
    var PIVechicleData = await Database.get("PIVechicleData");
    var activityId = PIVechicleData?.activityId;
    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 = await Database.get("PIGonePoseDetection");
    noOfImagesGoneForPoseDection =
      PIGonePoseDetection.GoneposeDetectionCount + 1;
    await Database.update("PIGonePoseDetection", {
      GoneposeDetectionCount: noOfImagesGoneForPoseDection,
    });
    UELogEvent("gathered data in callChassisPoseDetection", {
      formdata: JSON.stringify(formdata),
      PIGonePoseDetection: JSON.stringify(PIGonePoseDetection),
    });

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

    setISLoading(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 = await Database.get(
      "PIPoseDetectionCompleted"
    );
    noOfImagesPoseDetedImages =
      PIPoseDetectionCompleted?.poseDetectionCompletedCount + 1;
    console.log(")))))))))))))))))))))))", noOfImagesPoseDetedImages);
    await Database.update("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?.retryCount > 0) {
        //upload and navigate to thank you screen
        UELogEvent("upload and navigate to thank you screen", {
          "Retry count": JSON.stringify(PIRetryCount?.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(activityId, PIRetryCount, ".jpg", false);

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

        var ext = DocumentImageName == "VDO" ? ".mp4" : ".jpg";
        await initMediaFile(
          uri,
          DocumentImageName,
          ext,
          "poseFailed",
          () => {}
        );

        saveRetryDataInRedux(activityId, uri);
        offlinePIDataToRealm(false);
        if (isLast) {
          UELogEvent("started executing navigationFunc() in else if if", {
            isLast: JSON.stringify(isLast),
          });
          navigationFunc();
        }
      }
    }
  };

  const addSensorImageData = (activityId, PIRetryCount, ext, ImageStatus) => {
    var attemptCount = PIRetryCount?.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) => {
    try {
      var PIVechicleData = await Database.get("PIVechicleData");
      var PIRetryCount = await Database.get("PIRetryCount");
      var activityId = PIVechicleData?.activityId;
      UELogEvent("callPoseDetection api call started", {
        uri: JSON.stringify(uri),
      });
      let isBlur = true,
        isDark = true;
      let imgPose;
      let poseName;
      let isDetect;

      var PIGonePoseDetection = await Database.get("PIGonePoseDetection");
      noOfImagesGoneForPoseDection =
        PIGonePoseDetection.GoneposeDetectionCount + 1;
      await Database.update("PIGonePoseDetection", {
        GoneposeDetectionCount: noOfImagesGoneForPoseDection,
      });

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

      var formdata = new FormData();
      formdata.append("file", {
        uri: uri,
        name: activityId + "_" + DocumentImageName + ".jpg",
        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(formdata);

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

      var PIPoseDetectionCompleted = await Database.get(
        "PIPoseDetectionCompleted"
      );
      noOfImagesPoseDetedImages =
        PIPoseDetectionCompleted?.poseDetectionCompletedCount + 1;
      console.log(")))))))))))))))))))))))", noOfImagesPoseDetedImages);
      await Database.update("PIPoseDetectionCompleted", {
        poseDetectionCompletedCount: noOfImagesPoseDetedImages,
      });

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

      console.log("POSE RESPONCE >> ", 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;
      console.log("isBlur : ", isBlur);
      console.log("isDalrk : ", isDark);
      console.log("imgPose : ", imgPose);

      poseName = 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?.retryCount > 0) {
          // upload image without pose detection
          UELogEvent("Uploading image without pose detection", {
            "Retry Count": JSON.stringify(PIRetryCount?.retryCount),
          });
          uploadImage(uri);
        } else {
          // try two time to upload image
          UELogEvent("Trying to upload two time", {
            uri: JSON.stringify(uri),
          });
          var ext = DocumentImageName == "VDO" ? ".mp4" : ".jpg";
          await initMediaFile(
            uri,
            DocumentImageName,
            ext,
            "poseFailed",
            () => {}
          );
          saveRetryDataInRedux(activityId, uri);
          offlinePIDataToRealm(false);
          if (isLast) {
            navigationFunc();
          }
        }
      }
    } catch (error) {
      console.log("Error : catch previewImages.js : ", error);
    }
  };

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

    if (iOS) {
      /*
       * getModel() method lags on IOS devices, getDeviceId() is reccomended for same.
       */
      model = DeviceInfo.getDeviceId();
    } else {
      model = DeviceInfo.getModel();
    }
    if (model === undefined || model === null) {
      model = "NA";
    }

    DeviceInfo.getManufacturer().then((manfacture) => {
      make = manfacture;
      if (make === undefined || make === null) {
        make = "NA";
      }
    });
  };

  //upload images
  const uploadImage = async (uri) => {
    if (is2Wflow(activityTypeId)) {
      initMediaFile(uri, DocumentImageName, ext, "poseSuccess", () => {});
    } else {
      initMediaFile(uri, DocumentImageName, ext, "pending", () => {});
    }
    if (isLast) {
      UELogEvent("started navigationFunc() in upload image");
      navigationFunc();
    }
  };

  const storeOfflineData = async (uri, DocumentImageName) => {
    const status = "pending";
    if (canGoVideoPi(activityTypeId) || isCVFlow(activityTypeId)) {
      var ext = DocumentImageName == "VDO" ? ".mp4" : ".jpg";
      await initMediaFile(uri, DocumentImageName, ext, status, () => {});
      saveRetryDataInRedux(activityId, uri);
      offlinePIDataToRealm(false);
    } else {
      var ext = DocumentImageName == "VDO" ? ".mp4" : ".jpg";
      initMediaFile(uri, DocumentImageName, ext, status, () => {});
      saveRetryDataInRedux(activityId, uri);
      offlinePIDataToRealm(false);
    }
  };

  // create image with info
  const createImageWithName = async (activityId) => {
    if (DocumentImageName == "VDO" || ext == ".mp4") {
      if (isInternetReachable) {
        UELogMessage("Creating Video", {
          title: VIDEO_TITLE,
          titleHindi: VIDEO_TITLE_HN,
          imageData: ImageData,
        });
        console.log(
          "*** PreviewImage createImageWithName before uploadImage ImageData: ",
          ImageData,
          DocumentImageName
        );
        uploadImage(ImageData);
        console.log(
          "*** PreviewImage createImageWithName after uploadImage ImageData: ",
          ImageData,
          DocumentImageName
        );
        // When user has captured the video
        // then only start the background upload
        await Database.set("PI2WOnProgress", "false");
        await storeOfflineData(ImageData, DocumentImageName);
        console.log(
          "*** PreviewImage createImageWithName after storeOfflineData : ",
          ImageData,
          DocumentImageName
        );
        await navigationFunc();
      } else {
        UELogMessage("Not connected to internet while creating video", {
          title: VIDEO_TITLE,
          titleHindi: VIDEO_TITLE_HN,
          imageData: ImageData,
        });
        await storeOfflineData(ImageData, DocumentImageName);
        // Alert.alert("Please check your internet connection !!!");
      }
      setISLoading(false);
      if (!isLast) {
        navigationFunc();
      }
    } 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) => {
            const storeImage = async (uri) => {
              setISLoading(false);
              // check valid image
              var validImage = await validateImage(uri);
              if (!validImage) {
                return;
              } else {
                if (!isLast) {
                  navigationFunc();
                }
              }
              var AppLoginStatus = await Database.get("AppLoginStatus");
              const PIRetryCount = await Database.get("PIRetryCount");
              console.log(
                "*** PreviewImage captureRef PIRetryCount: " +
                  JSON.stringify(PIRetryCount)
              );
              console.log(
                "QQQQQQQQQQQQ",
                activityTypeId,
                is2Wflow(activityTypeId),
                isCVFlow(activityTypeId),
                AppLoginStatus?.userType,
                isInternetReachable
              );
              UELogMessage("Setting Final Image Path", {
                uri: uri,
              });
              SetFinalImagePath(uri);
              if (
                title == SELFI_IMAGE ||
                titleHn == SELFI_IMAGE_HN ||
                isCVFlow(activityTypeId) ||
                AppLoginStatus?.userType == "OEMDealer" ||
                DocumentImageName == "SF" ||
                DocumentImageName == "CNG" ||
                DocumentImageName == "IWS" ||
                PIRetryCount?.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?.userType,
                    DocumentImageName: DocumentImageName,
                  }),
                });
                if (isInternetReachable) {
                  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,
                  });
                  await storeOfflineData(uri, DocumentImageName);
                  // 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 (isInternetReachable) {
                    UELogEvent(
                      "internet connected while calling callChassisPoseDetection",
                      {
                        uri: uri,
                      }
                    );
                    callChassisPoseDetection(uri);
                  } else {
                    UELogEvent(
                      "internet not connected while calling callChassisPoseDetection",
                      {
                        uri: uri,
                      }
                    );
                    await storeOfflineData(uri, DocumentImageName);
                    // Alert.alert("Please check your internet connection !!!");
                  }
                } else if (
                  is2Wflow(activityTypeId) // 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 (isInternetReachable) {
                    UELogEvent(
                      "Internet connected while calling callPoseDetection 2w",
                      {
                        uri: uri,
                      }
                    );
                    callPoseDetection(uri);
                  } else {
                    UELogEvent(
                      "internet not connected while calling callPoseDetection 2w",
                      {
                        uri: uri,
                      }
                    );
                    await storeOfflineData(uri, DocumentImageName);
                    // Alert.alert("Please check your internet connection !!!");
                  }
                } else if (canGoVideoPi(activityTypeId)) {
                  // call API for 4W pose detection
                  UELogEvent("call API for 4W pose detection", {
                    uri: uri,
                  });
                  if (isInternetReachable) {
                    UELogEvent(
                      "internet not connected while calling callPoseDetection 4w",
                      {
                        uri: uri,
                      }
                    );
                    callPoseDetection(uri);
                  } else {
                    UELogEvent(
                      "internet not connected while calling callPoseDetection 4w",
                      {
                        uri: uri,
                      }
                    );
                    await storeOfflineData(uri, DocumentImageName);
                    // Alert.alert("Please check your internet connection !!!");
                  }
                }
              }
            };
            storeImage(uri);
          },

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

  const validateImage = async (uri) => {
    try {
      const status = await RNFetchBlob.fs.exists(uri);
      console.log("validateImage : status :", status);
      if (status) {
        return status;
      } else {
        Alert.alert(
          "Error while capture image",
          "Please capture image again!",
          [
            {
              text: "Ok",
              onPress: () => {
                navigation.goBack();
              },
            },
          ]
        );
        return false;
      }
    } catch (error) {
      console.log("Error in validateImage : ", error);
      return false;
    }
  };

  const saveRetryDataInRedux = async (activityId, 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, "  ")
    );
  };

  // retry redux length
  const callRetrayDataCount = () => {
    reTryDataLen = RetryImageData?.retryImageInfo?.length;
    UELogEvent("callRetrayDataCount started", {
      "retry data length": reTryDataLen,
    });
    console.log("REDUX LEN >", reTryDataLen);
    return <View />;
  };

  const onProceedButton = async () => {
    var PIRetryCount = await Database.get("PIRetryCount");
    var PIclickedCount = await Database.get("PIclickedCount");
    var PIVechicleData = await Database.get("PIVechicleData");
    var activityId = PIVechicleData?.activityId;
    console.log(
      "*** PreviewImage Proceed PIclickedCount: " +
        JSON.stringify(PIclickedCount)
    );

    if (PIRetryCount?.retryCount == 0) {
      var ImageClickedCount = PIclickedCount?.clickedCount;
      ImageClickedCount = ImageClickedCount + 1;
      // dispatch({
      //   type: 'IMAGE_CLICKED_COUNT',
      //   payload: {
      //       ImageClickedCount: ImageClickedCount,
      //     },
      // });

      await Database.update("PIclickedCount", {
        clickedCount: ImageClickedCount,
      });

      console.log("Click COUNT >>> ", PIclickedCount?.clickedCount);
    }
    // if (DocumentImageName !== CHASSIS_NUMBER) {
    //   setISLoading(true);
    // }
    setISLoading(true);
    await createImageWithName(activityId);
    // else if (title == SELFI_IMAGE || titleHn == SELFI_IMAGE_HN || activityTypeId == ACTIVITY_TYPE_MOTOR_CVOD_PRE_INSPECTION_SELF_SURVEY) {
    //   navigationFunc();
    // }
  };

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

  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={false}
              // style={styles.productImageStyle}
            />
          ) : (
            <ViewShot ref={imageref}>
              <View>
                <Image
                  source={{
                    uri: iOS
                      ? ImageData.replace("file://", "")
                      : "file://" + ImageData,
                  }}
                  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.goBack();
              }}
            >
              <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={() => {
                debouncedCall();
              }}
            >
              <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>
    </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: maxSize,
    height: 48,
    backgroundColor: "#000000",
    opacity: 0.58,
    justifyContent: "center",
  },
  infoText: {
    fontFamily: "Muli-SemiBold",
    fontSize: 14,
    color: "#FFFFFF",
    marginLeft: 24,
    marginRight: 24,
  },
});
