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";
//Global variables
var AppLoginStatus = realm.objects("AppLoginStatus");

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;

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 UploadImageData = useSelector((state) => state.UploadImageData);
  const imageClickedCountDetails = useSelector(
    (state) => state.imageClickedCountDetails
  );
  const isLastData = useSelector((state) => state.isLastData);
  const [isLoading, setISsLoading] = useState(false);
  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("");

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

  var uploadedImageCount = PIUploadedCount[0]?.uploadedCount;
  var ImageClickedCount = PIclickedCount[0]?.clickedCount;
  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
    );
  };
  // 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 = () => {
    console.log("Retry Data from Redux");
    console.log("RETRY_DATA_LEN >>>", reTryDataLen);
    // console.log('isInternetConnected >>>', isInternetConnected);

    setISsLoading(false);
    if (isLast && reTryDataLen == 0 && isInternetConnected) {
      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");
    } else {
      if (isLast && reTryDataLen != 0) {
        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 > ');
        if (title == RC_BOOK || titleHn == RC_BOOK_HN) {
          navigation.navigate("PI", { photo: "", isRCBook: true });
        } else {
          navigation.navigate("PI");
        }
      }
    }
  };

  //CALL CHASSIS POSE DETECTION
  const callChassisPoseDetection = async (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);

    const ChassisPoseDetectionData = await chassiesPoseDetetction({
      body: formdata,
    });
    if (
      ChassisPoseDetectionData?.match_ratio >
      ChassisPoseDetectionData?.threshold_match_ratio
    ) {
      uploadImage(uri);

      //adding sensor data
      sensorImageDetails.push({
        attemptCount: PIRetryCount[0]?.retryCount + 1,
        fileName: activityId + "_" + DocumentImageName + ".jpg",
        latitude: currentLatitude,
        longitude: currentLongitude,
        pose: DocumentImageName,
        success: true,
        timestamp: new Date().getTime(),
      });
      dispatch({
        type: "SENSOR_DETAILS",
        payload: sensorImageDetails,
      });
      dispatch({
        type: "REMOVE_BY_TITLE",
        payload: title,
      });
    } else {
      if (PIRetryCount[0]?.retryCount >= 2) {
        //upload and navigate to thank you screen
        uploadImage(uri);

        //adding sensor data
        sensorImageDetails.push({
          attemptCount: PIRetryCount[0]?.retryCount + 1,
          fileName: activityId + "_" + DocumentImageName + ".jpg",
          latitude: currentLatitude,
          longitude: currentLongitude,
          pose: DocumentImageName,
          success: true,
          timestamp: new Date().getTime(),
        });
        dispatch({
          type: "SENSOR_DETAILS",
          payload: sensorImageDetails,
        });

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

        if (isLast) {
          navigationFunc();
        }
      } else {
        //adding sensor data
        sensorImageDetails.push({
          attemptCount: PIRetryCount[0]?.retryCount + 1,
          fileName: activityId + "_" + DocumentImageName + ".jpg",
          latitude: currentLatitude,
          longitude: currentLongitude,
          pose: DocumentImageName,
          success: true,
          timestamp: new Date().getTime(),
        });

        dispatch({
          type: "SENSOR_DETAILS",
          payload: sensorImageDetails,
        });

        //add data to redux
        saveRetryDataInRedux(uri);

        if (isLast) {
          navigationFunc();
        }
      }
    }
  };

  // POSE DETECTION API CALL
  const callPoseDetection = async (uri) => {
    let isBlur = true,
      isDark = true;
    let imgPose;
    let poseName;
    let isDetect;
    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");

    const poseDetectionData = await poseDetection({
      body: formdata,
    });
    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) {
      var isIncorrect = false;
      var poseNameNotDoc = get2WPoseFileNotDoc(); // gating Doc
      poseNameNotDoc.forEach((item) => {
        //RCB
        if (item == DocumentImageName) {
          isIncorrect = true;
        }
      });

      if (!isIncorrect) {
        isDetect == true;
      }
    } else {
      // 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) {
      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;
      } else {
        if (isDark) message = image_pose_dark;
        if (isBlur) message = image_pose_blur;
        if (!isDark && !isBlur) message = image_pose_wrong;
      }
    }

    if (!isBlur && !isDark && isDetect) {
      console.log(
        "Uploading An Image ===>",
        "isDetect=",
        isDetect,
        " imgPose=",
        imgPose,
        " DocumentImageName=",
        DocumentImageName
      );
      //if image is good then excute this block
      // upload image
      uploadImage(uri);
      //create sensor data ==> if image is uploaded
      sensorImageDetails.push({
        attemptCount: PIRetryCount[0]?.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");
    } else {
      //create sensor data ==> if image not  uploaded
      console.log(
        "EEEEEEEEEEEEEEEEEEEEEEE",
        activityId + "_" + DocumentImageName + ".jpg"
      );

      sensorImageDetails.push({
        attemptCount: PIRetryCount[0]?.retryCount + 1,
        fileName: activityId + "_" + DocumentImageName + ".jpg",
        latitude: currentLatitude,
        longitude: currentLongitude,
        pose: DocumentImageName,
        success: false,
        timestamp: new Date().getTime(),
      });

      dispatch({
        type: "SENSOR_DETAILS",
        payload: sensorImageDetails,
      });

      // GO FOR RE-TRY
      //save the details to redux
      if (PIRetryCount[0]?.retryCount >= 2) {
        // upload image without pose detection
        uploadImage(uri);
      } else {
        // try two time to upload image
        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) => {
    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) => {
      console.log(
        "File Uploaded => ",
        Math.round(event.loaded * 100) / event.total
      );
    };
    console.log(
      "IN UPLOAD => DOCUMENT STATUS ==> isLast = ",
      isLast.toString()
    );
    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",
    };
    formData.append("file", {
      uri: uri,
      type: "image/jpeg",
      fileName: activityId + "_" + DocumentImageName,
      name: activityId + "_" + DocumentImageName + ext,
    });
    formData.append("documentData", JSON.stringify(documentUploadData));

    xhr.upload.addEventListener("progress", handleProgress);
    xhr.addEventListener("load", () => {
      console.log("Uploaded", DocumentImageName);

      // uploadedImageCount = uploadedImageCount + 1;
      // console.log("@@@@@@@@@@@@@ HOW MANY IMAGES UPLOADED => ",uploadedImageCount);
      // dispatch({
      //   type: 'UPLOAD_IMAGE',
      //   payload: {
      //       uploadImageCount: uploadedImageCount,
      //     },
      // });
      uploadedImageCount = uploadedImageCount + 1;
      console.log("HOW MANY IMAGES UPLOADED => ", 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", () => {
      saveRetryDataInRedux(uri);
      console.log("abort");
    });
    xhr.addEventListener("error", () => {
      saveRetryDataInRedux(uri);
      console.log("error");
    });
    xhr.addEventListener("timeout", () => {
      saveRetryDataInRedux(uri);
      console.log("timeout");
    });
    xhr.open("POST", SELFSURVEYSERVICE_DOCUMENT_URL);
    xhr.setRequestHeader(
      "Accept",
      "*/*",
      "Content-Type",
      "multipart/form-data"
    );
    xhr.send(formData);

    if (isLast) {
      navigationFunc();
    }
  };

  // create image with info
  const createImageWithName = async () => {
    if (title == VIDEO_TITLE || titleHn == VIDEO_TITLE_HN) {
      if (isInternetConnected) {
        uploadImage(ImageData);
      } else {
        saveRetryDataInRedux(ImageData);
      }
    } else {
      try {
        await captureRef(imageref, {
          format: "jpg",
          quality: 0.8,
        }).then(
          (uri) => {
            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
            );
            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"
            ) {
              if (isInternetConnected) {
                uploadImage(uri);
              } else {
                saveRetryDataInRedux(uri);
              }
              reactotron.log("IN SELFI");
            } else {
              if (DocumentImageName === CHASSIS_NUMBER) {
                // call API for chassies number pose detection
                if (isInternetConnected) {
                  callChassisPoseDetection(uri);
                } else {
                  saveRetryDataInRedux(uri);
                }
              } else if (
                activityTypeId ==
                ACTIVITY_TYPE_MOTOR_2W_PRE_INSPECTION_SELF_SURVEY // for 2W
              ) {
                console.log("called from 2W Image Creation");
                // call APi for pose detection for 2W
                if (isInternetConnected) {
                  callPoseDetection(uri);
                } else {
                  saveRetryDataInRedux(uri);
                }
              } 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
                if (isInternetConnected) {
                  callPoseDetection(uri);
                } else {
                  saveRetryDataInRedux(uri);
                }
              }
            }
          },

          (error) => console.error("Oops, snapshot failed", error)
        );
      } catch (err) {
        console.log("Error in view shot", err);
      }
    }
  };

  const saveRetryDataInRedux = (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) {
      navigationFunc();
    }

    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;
    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: SCREEN_HEIGHT,
                    height: SCREEN_WIDTH - 50,
                    resizeMode: "contain",
                    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"
                );
                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();
                // }
                if (PIRetryCount[0]?.retryCount == 0) {
                  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 >>> ", ImageClickedCount);
                }
              }}
            >
              <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,
  },
});
