import React, { Component } from "react";
import {
  Alert,
  FlatList,
  Image,
  KeyboardAvoidingView,
  PermissionsAndroid,
  Platform,
  StyleSheet,
  Text,
  View,
} from "react-native";
import { instructionData } from "./common/Services/instruction";
import {
  VIDEO_TITLE,
  VIDEO_TITLE_HN,
  RC_BOOK,
  RC_BOOK_HN,
  WEB_REQUEST,
  ANDROID_REQUEST,
  CNG,
  CNG_HN,
  PUC_Hn,
  PUC,
  ODOMETER,
  ODOMETER_HN,
  isCVFlow,
} from "./common/Constants";
import Header from "./Screens/Header";
import VehicleSurveyInstruction from "./Screens/VehicleSurveyInstruction";
import Orientation from "react-native-orientation";
import {
  PrimaryButton,
  DashedButton,
  Spinner,
} from "react-native-digitcamera/src/common/ThemedComponents";
import { translate } from "react-native-digitcamera/src/common/localize/i18n";
import { connect } from "react-redux";
import { ScrollView, TouchableOpacity } from "react-native-gesture-handler";
import Modal from "react-native-modal";
import Database from "../../../Components/common/DAsyncStorage";
import reactotron from "reactotron-react-native";
import Geolocation from "react-native-geolocation-service";
// import {
//   startCapturingSensorData,
//   unsubscribeSensors,
// } from "./common/SensorData";
import { measureConnectionSpeed } from "react-native-network-bandwith-speed";
import { retryImageAction } from "./redux/actions/retryImageAction";

import { SafeAreaView } from "react-native-safe-area-context";
import Colors from "react-native-digitcamera/src/common/Colors";
import {
  errorRecord,
  firebaseAttributes,
  firebaseEvents,
} from "react-native-digitcamera/src/common/libEventLog/libCrashlytics/libCrashlyticsEvent";
import NetInfo from "@react-native-community/netinfo";
import { getDimension } from "./common/scaling";
const { SCREEN_HEIGHT, SCREEN_WIDTH } = getDimension();
var isDataSet = true;
const iOS = Platform.OS === "ios";
const camera = require("./common/Image/camera.png");
const recorder = require("./common/Image/recorder.png");
const tick = require("./common/Image/tick.png");
const deleteIcon = require("./common/Image/deleteIcon.png");
const cameraTip = require("./common/Image/cameraTip.png");
import {
  UELogEvent,
  UELogMessage,
} from "./common/libEventLog/UserExperior/LibUserExperior";
import { getCurrentActivity } from "react-native-digitcamera/src/Screens/OfflineFlow/CommonFunc";
import { ODOMETER_READING_REGEX } from "../../../Components/common/Constants";

let index;
let isLast = false;
// Global Veriables
let instuction = [];
var Retryinstuction = [];

var RealmData;
var PIRetryCount;
var ishandleAddNewImage;

var RCBCountInRetry;
var activityId, activityTypeId, licensePlateNumber, quoteNumber;
var DataSpeed;
var count;
var RealmInstructionData;
var RealmRetryInstructionData;
var vechicleData;
var PIStartOver;
var realmIndex;
var PIRCBCount;

const PhotoTipModal = ({ isVisible, onBackdropPress, onClose, onOKPress }) => {
  return (
    <Modal
      isVisible={isVisible}
      onBackdropPress={onBackdropPress}
      onModalHide={onClose}
      style={{
        justifyContent: "flex-end",
        margin: 0,
      }}
      statusBarTranslucent
    >
      <PhotoTipContent onOKPress={onOKPress} />
    </Modal>
  );
};

// photo tip modal
PhotoTipContent = ({ onOKPress }) => {
  return (
    <View
      style={{
        backgroundColor: "white",
        justifyContent: "space-evenly",
        alignItems: "center",
        height: SCREEN_WIDTH * 0.9,
      }}
    >
      <View style={{}}>
        <Image
          source={cameraTip}
          style={{
            height: SCREEN_WIDTH * 0.5,
            resizeMode: "contain",
            alignSelf: "center",
          }}
        />
      </View>
      <View style={{ justifyContent: "space-between" }}>
        <Text style={[styles.tipSubText]}>
          {translate(
            "Hold the phone horizontally for capturing better photos of the vehicle"
          )}
        </Text>
        <PrimaryButton style={{}} onPress={onOKPress}>
          {translate("Ok, Got it")}
        </PrimaryButton>
      </View>
    </View>
  );
};

class PI extends Component {
  constructor(props) {
    super(props);
    index = 0;
    this.state = {
      title: "",
      titleHn: "",
      subTitle: "",
      subTitleHn: "",
      image:
        "https://d2h44aw7l5xdvz.cloudfront.net/assets/gif/time-animation-loader.gif",
      points: [],
      totalSteps: "",
      staincil: "",
      imageName: "",
      show_RC_front_Button: true,
      show_RC_back_Button: true,
      addMoreRCImages: [],
      isTipModalVisible: false,
      disableButton: true,
      isOdometer: false,
      isLoading: true,
      isDataUpdate: true,
    };
  }

  componentWillUnmount() {
    if (this.unsubscribeFocus) {
      this.unsubscribeFocus();
    }
  }

  makeImmersive = () => {
    let Immersive = undefined;
    let restoreImmersive = undefined;
    if (!iOS) {
      Immersive = require("react-native-immersive").Immersive;
      Immersive.setImmersive(true);
      restoreImmersive = () => {
        // __DEV__ && console.log("Immersive state changed!");
        // Immersive.setImmersive(true);
      };
      Immersive.addImmersiveListener(restoreImmersive);
    }
  };

  componentDidUpdate() {
    console.log("*** PI componentDidUpdate");
    // this.getData();
  }

  getData = async () => {
    try {
      console.log("************************ PI getData");
      RealmData = await Database.get("SelectedLang");
      PIRetryCount = await Database.get("PIRetryCount");
      RealmInstructionData = await Database.get("PIVechicleInstruction");
      RealmRetryInstructionData = await Database.get("PIOfflineData");
      vechicleData = await Database.get("PIVechicleData");
      PIStartOver = await Database.get("PIStartOver");
      realmIndex = await Database.get("PIINDEX");
      PIRCBCount = await Database.get("PIRCBCount");

      count = PIRCBCount.addMoreCount;

      UELogEvent("In PI.js Component Did Mount", {
        "Retry Count": JSON.stringify(PIRetryCount?.retryCount),
        Details: JSON.stringify({
          activityID: vechicleData.activityId,
          activityTypeId: activityTypeId,
          licensePlateNumber: licensePlateNumber,
          quoteNumber: quoteNumber,
        }),
      });
      if (this.props.activityData?.activityInfo?.toWithQuote) {
        activityId = this.props.activityData?.activityInfo?.activityId;
        activityTypeId = this.props.activityData?.activityInfo?.activityTypeId;
        licensePlateNumber =
          this.props.activityData?.activityInfo?.licensePlateNumber;
        quoteNumber = this.props.activityData?.activityInfo?.quoteNumber;
      } else {
        var PIVechicleData = await Database.get("PIVechicleData");
        activityId = PIVechicleData?.activityId;
        activityTypeId = PIVechicleData?.activityTypeId;
        licensePlateNumber = PIVechicleData?.licensePlateNumber;
        quoteNumber = PIVechicleData?.quoteNumber;
      }
      this.props.vehicleDetailsAction({
        activityID: activityId,
        activityTypeId: activityTypeId,
        licensePlateNumber: licensePlateNumber,
        quoteNumber: quoteNumber,
      });
      isLast = false;
      //  call retry logic
      console.log(
        "*************************************** PI PIRetryCount?.retryCount",
        PIRetryCount?.retryCount
      );
      if (PIRetryCount?.retryCount > 0) {
        if (PIRetryCount?.isAddNewImageData) {
          index = 0;
        }
        if (isDataSet == true) {
          isDataSet = false;
          Retryinstuction = await this.getInvalidImagesData();
        }

        this.updateRetryInstruction();
      } else {
        UELogEvent("Preinspection First Try...");
        // frist try
        // this.callInstructionServices();
        instuction = [];
        let dbInstruction = RealmInstructionData?.instuction;
        if (dbInstruction === undefined || dbInstruction.length <= 0) {
          this.props.navigation.navigate("WithQuote");
          Alert.alert(
            "Try Again!",
            "We are unable to load guiding information for you."
          );
          return;
        }
        instuction = JSON.parse(dbInstruction);
        console.log("*** PI getData instuction: ", instuction);
        this.updateInstructionData();
      }
      this.setState({ isLoading: false });
    } catch (error) {
      console.log("Error in DidM in PI ", error);
    }
  };

  async getInvalidImagesData() {
    const VehicleInstructions = await Database.get("PIVechicleInstruction"); // all instruction
    const instructions = JSON.parse(VehicleInstructions.instuction);
    const mediaStatus = await Database.get("PIMediaStatus"); // failed and uploaded images

    var PIVechicleData = await Database.get("PIVechicleData");
    var activityId = PIVechicleData?.activityId;

    var currentActivity = mediaStatus.filter((item) => {
      return item.activityId == activityId;
    });

    console.log(
      "PI.js  mediaStatus",
      JSON.stringify(currentActivity, null, "  "),
      currentActivity[0]?.mediaUpload?.length
    );
    const invalidImagesData = [];

    if (instructions && mediaStatus) {
      if (
        instructions.length != 0 &&
        currentActivity[0]?.mediaUpload?.length != 0
      ) {
        //failed images
        const failedImagesData = currentActivity[0]?.mediaUpload?.filter(
          (item) => item?.status == "poseFailed"
        );
        console.log(
          "invalidImages.js  failedImagesData",
          JSON.stringify(failedImagesData, null, "  ")
        );

        //failed images with its instruction

        instructions.forEach((item) => {
          const newObj = failedImagesData.find(
            (failedImageItem) => failedImageItem.imageName === item.imageName
          );
          if (newObj !== undefined) {
            item.imageUri = newObj.uri;
            console.log(item);
            invalidImagesData.push(item);
          }
        });
      }
    }
    return invalidImagesData;
  }

  componentDidMount() {
    this.unsubscribeFocus = this.props.navigation.addListener("focus", () => {
      this.setState({ isLoading: true });
      this.getData();
      this.makeImmersive();
      Orientation.lockToLandscapeLeft();
    });
    this.getPermission();
    // startCapturingSensorData();
  }

  async getAndroidPermission() {
    const grantedWrite = await PermissionsAndroid.request(
      PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE
    );
    const grantedRead = await PermissionsAndroid.request(
      PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE
    );

    const grantedPhoneState = await PermissionsAndroid.request(
      PermissionsAndroid.PERMISSIONS.READ_PHONE_STATE
    );

    if (
      grantedWrite !== PermissionsAndroid.RESULTS.GRANTED ||
      grantedRead !== PermissionsAndroid.RESULTS.GRANTED ||
      grantedPhoneState !== PermissionsAndroid.RESULTS.GRANTED
    )
      Alert.alert(translate("Permission denied"));
  }

  async getPermission() {
    if (Platform.OS === "android") {
      await this.getAndroidPermission();
    }
  }

  //Camera and Audio
  async getAndroidCameraAudioPermission() {
    const grantedCamera = await PermissionsAndroid.request(
      PermissionsAndroid.PERMISSIONS.CAMERA
    );
    const grantedAudio = await PermissionsAndroid.request(
      PermissionsAndroid.PERMISSIONS.RECORD_AUDIO
    );

    if (
      grantedCamera !== PermissionsAndroid.RESULTS.GRANTED ||
      grantedAudio !== PermissionsAndroid.RESULTS.GRANTED
    )
      Alert.alert(translate("Permission denied"));
  }

  async getCameraAudioPermission() {
    if (Platform.OS === "android") {
      await this.getAndroidCameraAudioPermission();
    }
  }

  updateRetryInstruction = async () => {
    try {
      UELogEvent("updateRetryInstruction is started", {
        "Retry Instruction Length": JSON.stringify(Retryinstuction.length),
        Index: JSON.stringify(index),
      });
      // for Odometer to handlle proceed button.
      if (Retryinstuction[index]?.imageName == "DBD") {
        this.setState({ isOdometer: true });
      } else {
        this.setState({ isOdometer: false });
      }
      //for checking how many RCB images are in retry
      RCBCountInRetry = Retryinstuction.filter((item) => {
        console.log("IN RCB FILTER >>> ", item.imageName);
        return item.imageName.includes("RCB");
      }).length;
      PIRetryCount = await Database.get("PIRetryCount");
      if (PIRetryCount?.isAddNewImageData) {
        this.setState({
          show_RC_back_Button: true,
          show_RC_front_Button: true,
        });

        // set new data And Clear the old of retry image data only when click on retake in incorectImages.js
        index = 0;

        // this.props.retryImageAction();
        this.props.retryCountAction({
          retryCount: PIRetryCount?.retryCount,
          index: PIRetryCount?.index,
          isAddNewImageData: false,
        });

        var realmRetryCount = PIRetryCount?.retryCount;
        var realmRetryIndex = PIRetryCount?.index;
        await Database.update("PIRetryCount", {
          retryCount: realmRetryCount,
          index: realmRetryIndex,
          isAddNewImageData: false,
        });
      }
      console.log(
        "33333333333333333333333333333",
        JSON.stringify(Retryinstuction[index]?.stepAssests, null, "  ")
      );
      if (index < Retryinstuction?.length) {
        this.setState({
          title: Retryinstuction[index]?.stepTitle,
          titleHn: Retryinstuction[index]?.stepTitleHn,

          staincil: Retryinstuction[index]?.stepStencilAssests,
          imageName: Retryinstuction[index]?.imageName,

          subTitle: Retryinstuction[index]?.description,
          subTitleHn: Retryinstuction[index]?.descriptionHn,

          image: Retryinstuction[index]?.stepAssests,
          points: Retryinstuction[index]?.TSurveyInstructions,
          totalSteps: Retryinstuction?.length,
        });
      }
      UELogEvent("updateRetryInstruction ended in try", {
        Details: JSON.stringify({
          title: Retryinstuction[index]?.stepTitle,
          titleHn: Retryinstuction[index]?.stepTitleHn,

          staincil: Retryinstuction[index]?.stepStencilAssests,
          imageName: Retryinstuction[index]?.imageName,

          subTitle: Retryinstuction[index]?.description,
          subTitleHn: Retryinstuction[index]?.descriptionHn,

          image: Retryinstuction[index]?.stepAssests,
          points: Retryinstuction[index]?.TSurveyInstructions,
          totalSteps: Retryinstuction?.length,
        }),
      });
    } catch (error) {
      UELogEvent("Update Retry Instruction ended in catch", {
        Error: JSON.stringify(error),
      });
      firebaseAttributes(error);
      errorRecord(error);
      console.log("Error in updateRetryInstruction() => ", error);
    }
  };
  // update
  updateInstructionData() {
    console.log("is last", isLast, index);

    // for Odometer to handlle proceed button.
    if (instuction[index]?.imageName == "DBD") {
      this.setState({ isOdometer: true });
    } else {
      this.setState({ isOdometer: false });
    }
    if (index < instuction.length) {
      this.setState({
        title: instuction[index]?.stepTitle,
        titleHn: instuction[index]?.stepTitleHn,

        staincil: instuction[index]?.stepStencilAssests,
        imageName: instuction[index]?.imageName,

        subTitle: instuction[index]?.description,
        subTitleHn: instuction[index]?.descriptionHn,

        image: instuction[index]?.stepAssests,
        points: instuction[index]?.TSurveyInstructions,
        totalSteps: instuction?.length,
      });
    }
  }

  // check type of request
  instructionWebOrAndroid(activityTypeId) {
    activityTypeId = this.getActivityTypeIdIfSSL(activityTypeId);
    return activityTypeId == 6 ||
      activityTypeId == 7 ||
      activityTypeId == 8 ||
      activityTypeId == 9 ||
      activityTypeId == 10 ||
      activityTypeId == 11 ||
      activityTypeId == 15 ||
      activityTypeId == 31
      ? WEB_REQUEST
      : ANDROID_REQUEST;
  }
  // get ssl
  getActivityTypeIdIfSSL(activityTypeId) {
    if (activityTypeId == 50) {
      // Used for SSL deeplink / mapping given by Gowtham
      activityTypeId = 5;
    } else if (activityTypeId == 49) {
      activityTypeId = 26;
    } else if (activityTypeId == 51) {
      activityTypeId = 30;
    }
    return activityTypeId;
  }
  // get instruction from API
  callInstructionServices = async () => {
    if (false) {
    } else {
      try {
        UELogEvent("callInstructionServices started", {
          "Activity Type Id": JSON.stringify(activityTypeId),
        });
        let requestTypeName = this.instructionWebOrAndroid(activityTypeId);
        UELogMessage("Response from instructionServices", {
          "Request Type Name": JSON.stringify(requestTypeName),
        });
        let requestTypeValue;
        if (requestTypeName == WEB_REQUEST) {
          requestTypeValue = 1;
        } else {
          requestTypeValue = 0;
        }

        UELogEvent("InstructionData service call started", {
          "Type Id": JSON.stringify(activityTypeId),
          "Request Value": JSON.stringify(requestTypeValue),
        });
        let V_instuction = await instructionData({
          typeId: activityTypeId,
          requestValue: requestTypeValue,
        });

        UELogMessage("Response from instructionData", {
          "Vehicle Instructions": JSON.stringify(V_instuction),
        });

        DataSpeed = await measureConnectionSpeed();

        if (DataSpeed.value > 0.001) {
          V_instuction.TSurveySteps.map((item) => {
            instuction.push(item);
          });
        } else {
          V_instuction.TSurveySteps.map((item) => {
            if (item.imageName != "VDO") {
              instuction.push(item);
            }
          });
        }
        // One Time call from here
        this.updateInstructionData();
      } catch (error) {
        UELogEvent("callInstructionServices ended in Catch", {
          Error: JSON.stringify(error),
        });
        firebaseAttributes(error);
        errorRecord(error);
      }
    }
  };
  //RC Book dashed button
  renderItem = ({ index, item }) => {
    return (
      <DashedButton
        // Title={this.props.route?.params?.photo?.split('/')[this.props.route?.params?.photo?.split('/').length - 1]}
        Title={activityId + "_" + "RCB2.jpg"}
        RightImage={deleteIcon}
        leftImage={tick}
        onDeletePress={() => {
          const newAddMoreRCImages = [...this.state.addMoreRCImages];
          newAddMoreRCImages.splice(index, 1);

          this.setState((state) => ({
            addMoreRCImages: newAddMoreRCImages,
          }));
        }}
      />
    );
  };

  //For RCB
  async navigateToCameraWithRetry_RCB(docName) {
    console.log("*** PI navigateToCameraWithRetry_RCB docName: ", docName);

    await this.getCameraAudioPermission();
    this.props.navigation.navigate("Camera", {
      title: Retryinstuction[index]?.title,
      titleHn: Retryinstuction[index]?.titleHn,

      stepStencilAssests: Retryinstuction[index]?.stepStencilAssests,
      DocumentImageName: docName,

      subTitle: Retryinstuction[index]?.subTitle,
      subTitleHn: Retryinstuction[index]?.subTitleHn,

      totalSteps: Retryinstuction?.length,
      points: Retryinstuction[index]?.points,
      image: Retryinstuction[index]?.image,
      isLast,

      TotalImage: instuction?.length,
      currentIndex: index, // using in preview screen for start capturing the sensor data
      retryCount: PIRetryCount?.retryCount, // using in preview screen for start capturing the sensor data
      licensePlateNumber: licensePlateNumber,
      activityTypeId: activityTypeId,
      activityId: activityId,
    });
    this.updateRetryInstruction();
    return 0;
  }
  // For RCB
  async navigateToCamera_RCB(docName) {
    await this.getCameraAudioPermission();
    reactotron.log("Document Name  >>>", instuction[index]?.imageName);
    console.log("*** PI navigateToCamera_RCB docName: ", docName);

    this.props.navigation.navigate("Camera", {
      title: instuction[index]?.stepTitle,
      titleHn: instuction[index]?.stepTitleHn,

      stepStencilAssests: instuction[index]?.stepStencilAssests,
      DocumentImageName: docName,

      subTitle: instuction[index]?.description,
      subTitleHn: instuction[index]?.descriptionHn,

      totalSteps: instuction?.length,
      points: instuction[index]?.TSurveyInstructions,
      image: instuction[index]?.stepAssests,
      isLast,

      TotalImage: instuction?.length,
      currentIndex: index, // using in preview screen for start capturing the sensor data
      retryCount: PIRetryCount?.retryCount, // using in preview screen for start capturing the sensor data
      licensePlateNumber: licensePlateNumber,
      activityTypeId: activityTypeId,
      activityId: activityId,
    });
    this.updateInstructionData();
    return 0;
  }
  // open camera
  async navigateToCamera(docName) {
    console.log("*** PI navigateToCamera before docName: ", docName);
    await this.getCameraAudioPermission();
    console.log(
      "*** PI navigateToCamera after instuction[index]?.imageName: ",
      instuction[index]?.imageName
    );
    reactotron.log("Document Name  >>>", instuction[index]?.imageName);

    this.props.navigation.navigate("Camera", {
      title: instuction[index]?.stepTitle,
      titleHn: instuction[index]?.stepTitleHn,

      stepStencilAssests: instuction[index]?.stepStencilAssests,
      DocumentImageName: docName,

      subTitle: instuction[index]?.description,
      subTitleHn: instuction[index]?.descriptionHn,

      totalSteps: instuction?.length,
      points: instuction[index]?.TSurveyInstructions,
      image: instuction[index]?.stepAssests,
      isLast,

      TotalImage: instuction?.length,
      currentIndex: index, // using in preview screen for start capturing the sensor data
      retryCount: PIRetryCount?.retryCount, // using in preview screen for start capturing the sensor data
      licensePlateNumber: licensePlateNumber,
      activityTypeId: activityTypeId,
      activityId: activityId,
      imageName: docName,
    });
    if (
      instuction[index]?.stepTitle == RC_BOOK ||
      instuction[index]?.stepTitleHn == RC_BOOK_HN
    ) {
      index = index;
      console.log(
        "*** PI navigateToCamera if instuction[index]?.stepTitle: ",
        instuction[index]?.stepTitle
      );
    } else {
      index = index + 1;
      console.log(
        "*** PI navigateToCamera else instuction[index]?.stepTitle: ",
        instuction[index]?.stepTitle
      );
    }
    this.updateInstructionData();
    return 0;
  }
  // open camera with retry
  navigateToCameraWithRetry(docName) {
    if (Retryinstuction[index] === undefined) {
      index = Retryinstuction.length - 1;
      Alert.alert("Oops!", "Something went wrong, please retry again");
      return;
    }
    this.props.navigation.navigate("Camera", {
      title: Retryinstuction[index]?.title,
      titleHn: Retryinstuction[index]?.titleHn,

      stepStencilAssests: Retryinstuction[index]?.stepStencilAssests,
      DocumentImageName: Retryinstuction[index]?.imageName,

      subTitle: Retryinstuction[index]?.subTitle,
      subTitleHn: Retryinstuction[index]?.subTitleHn,

      totalSteps: Retryinstuction?.length,
      points: Retryinstuction[index]?.points,
      image: Retryinstuction[index]?.image,
      isLast,

      TotalImage: instuction?.length,
      currentIndex: index, // using in preview screen for start capturing the sensor data
      retryCount: PIRetryCount?.retryCount, // using in preview screen for start capturing the sensor data
      licensePlateNumber: licensePlateNumber,
      activityTypeId: activityTypeId,
      activityId: activityId,
    });
    if (
      Retryinstuction[index]?.stepTitle == RC_BOOK ||
      Retryinstuction[index]?.stepTitleHn == RC_BOOK_HN
    ) {
      index = index;
    } else {
      index = index + 1;
    }
    this.updateRetryInstruction();
    return 0;
  }

  // For Proceed/capture /capture video
  onButtonPress = async () => {
    // for first time instruction
    try {
      console.log(
        "*** PI onButtonPress index: " +
          index +
          " totalInstructions: " +
          instuction?.length +
          " retryCount: " +
          PIRetryCount?.retryCount
      );
      if (index <= instuction?.length && PIRetryCount?.retryCount == 0) {
        //for tip modal
        // visible only in frist flow
        if (index == 0) {
          if (this.state.title != RC_BOOK && this.state.titleHn != RC_BOOK_HN) {
            this.setState({ isTipModalVisible: true });
          } else {
            this.setState({ isTipModalVisible: false });
            if (
              this.state.title == RC_BOOK ||
              this.state.titleHn == RC_BOOK_HN
            ) {
              index = index + 2;

              if (index >= instuction.length) {
                isLast = true;
              } else {
                isLast = false;
              }
              this.updateInstructionData();
            } else {
              if (index >= instuction.length - 1) {
                isLast = true;
              }

              console.log(
                "IS LAST >",
                index,
                instuction.length,
                index == instuction.length,
                isLast
              );
              this.navigateToCamera(this.state.imageName);
            }
          }
          //startCapturingSensorData();
        } else {
          this.setState({ isTipModalVisible: false });

          if (this.state.title == RC_BOOK || this.state.titleHn == RC_BOOK_HN) {
            index = index + 2;

            if (index >= instuction.length) {
              isLast = true;
            } else {
              isLast = false;
            }
            this.updateInstructionData();
          } else {
            if (index >= instuction.length - 1) {
              isLast = true;
            }

            console.log(
              "IS LAST >",
              index,
              instuction.length,
              index == instuction.length,
              isLast
            );
            this.navigateToCamera(this.state.imageName);
          }
        }
      }

      // ReTry
      else {
        if (this.state.title == RC_BOOK || this.state.titleHn == RC_BOOK_HN) {
          RCBCountInRetry = Retryinstuction.filter((item) => {
            return item.imageName.includes("RCB");
          }).length;

          index = index + RCBCountInRetry; // adding number of rc images user had clicked
          if (index >= Retryinstuction.length) {
            isLast = true;
          } else {
            isLast = false;
          }
          if (PIRetryCount?.retryCount > 0 && isLast) {
            if (
              isLast &&
              index != 0 &&
              this.props.RetryImageData.retryImageInfo.length <= 0
            ) {
              //  navigate to Progress you screen
              Orientation.lockToPortrait();
              var PIclickedCount = await Database.get("PIclickedCount");
              this.props.navigation.navigate("Progress", {
                TotalImage: PIclickedCount?.clickedCount,
              });
            }
          } else {
            console.log("is Last  >> ", isLast);
            if (isLast) {
              if (
                isCVFlow(activityTypeId) ||
                this.props.RetryImageData.retryImageInfo.length == 0
              ) {
                // "this.props.RetryImageData.retryImageInfo.length" this insted of "Retryinstuction?.length"  becouse require updated data here.
                if (
                  isLast &&
                  index != 0 &&
                  this.props.RetryImageData.retryImageInfo.length <= 0
                ) {
                  //  navigate to Progress you screen
                  Orientation.lockToPortrait();
                  var PIclickedCount = await Database.get("PIclickedCount");
                  this.props.navigation.navigate("Progress", {
                    TotalImage: PIclickedCount?.clickedCount,
                  });
                }
              } else {
                if (this.props.RetryImageData.retryImageInfo.length > 0) {
                  // "this.props.RetryImageData.retryImageInfo.length" this insted of "Retryinstuction?.length"  becouse require updated data here.
                  await Database.update("PIOfflineData", {
                    retryImageData: !!this.props.RetryImageData
                      ? JSON.stringify(this.props.RetryImageData)
                      : "",
                  });
                  this.props.navigation.navigate("InvalidImages", {
                    isLast: isLast,
                  });
                }
              }
            }
          }
          this.updateRetryInstruction();
        } else {
          // if in retry and image is not RC
          if (index >= Retryinstuction?.length - 1) {
            isLast = true;
          }
          // use data in retry redux
          this.navigateToCameraWithRetry(this.state.imageName);
        }
      }
      this.storeIndex(index);
    } catch (error) {
      console.log("OnButtonPress() ", error);
    }

    this.props.isLastAction({
      isLast: isLast,
    });
  };

  // For the Storing index in realm
  storeIndex = async (index) => {
    await Database.update("PIINDEX", {
      lastIndex: index,
    });
  };

  //save data in realm odometer
  async savaDataToRealm(value) {
    await Database.update("PIOdometerData", {
      readings: value,
    });
  }
  render() {
    if (RealmInstructionData == null || RealmInstructionData == undefined) {
      return <View style={{ backgroundColor: "white", flex: 1 }} />;
    }

    // Orientation.lockToLandscapeLeft();
    return (
      <KeyboardAvoidingView
        style={{ flex: 1 }}
        behavior={iOS ? "padding" : ""}
        enabled
      >
        <SafeAreaView
          style={styles.safeArea}
          edges={iOS ? ["bottom", "right", "top"] : []}
        >
          <View style={styles.main}>
            <Spinner loading={this.state.isLoading} />
            <Header
              customTitle="PI"
              currentStep={index}
              totalSteps={this.state.totalSteps}
              showSteps={true}
              onbackPress={() => {
                // first flow
                if (
                  index < instuction.length &&
                  PIRetryCount?.retryCount == 0 &&
                  index > 0
                ) {
                  index = index - 1;
                  this.setState({
                    title: instuction[index]?.stepTitle,
                    titleHn: instuction[index]?.stepTitleHn,

                    staincil: instuction[index]?.stepStencilAssests,
                    imageName: instuction[index]?.imageName,

                    subTitle: instuction[index]?.description,
                    subTitleHn: instuction[index]?.descriptionHn,

                    image: instuction[index]?.stepAssests,
                    points: instuction[index]?.TSurveyInstructions,
                    totalSteps: instuction?.length,
                  });
                } else {
                  if (index > 0) {
                    index = index - 1;
                    this.setState({
                      title: Retryinstuction[index]?.title,
                      titleHn: Retryinstuction[index]?.titleHn,

                      staincil: Retryinstuction[index]?.stepStencilAssests,
                      imageName: Retryinstuction[index]?.imageName,

                      subTitle: Retryinstuction[index]?.subTitle,
                      subTitleHn: Retryinstuction[index]?.subTitleHn,

                      image: Retryinstuction[index]?.image,
                      points: Retryinstuction[index]?.points,
                      totalSteps: RealmRetryInstructionData.length,
                    });
                  }
                  if (index <= 0) {
                    // for navigating to back screen
                    if (this.props.activityData?.activityInfo?.toWithQuote) {
                      if (this.props.activityData?.activityInfo?.toTutorial) {
                        this.props.navigation.pop();
                      } else {
                        this.props.navigation.pop();
                      }
                    } else {
                      this.props.navigation.pop();
                    }
                  }
                }
              }}
              onlanguagechange={() => {
                // this?.forceUpdate?.();
              }}
              shiftTitleToLeft={true}
            />
            {/* Instructions */}
            <VehicleSurveyInstruction
              title={
                RealmData?.PreferredLanguage === undefined ||
                RealmData?.PreferredLanguage == "en"
                  ? this.state.title
                  : this.state.titleHn
              }
              subTitle={
                RealmData?.PreferredLanguage === undefined ||
                RealmData?.PreferredLanguage == "en"
                  ? this.state.subTitle
                  : this.state.subTitleHn
              }
              image={this.state.image}
              points={this.state.points}
              odometerReading={(value) => {
                console.log("Odometer =>", this.state.imageName);
                if (value.length > 0 && value.match(ODOMETER_READING_REGEX)) {
                  this.setState({ disableButton: false });
                } else {
                  this.setState({ disableButton: true });
                }
                this.savaDataToRealm(value);
              }}
              DocumentName={this.state.imageName}
              onCaptureButton={() => {
                this.onButtonPress();
                this.setState((state) => ({
                  addMoreRCImages: [],
                }));
                count = 2;
                firebaseEvents(
                  "Capture_Image",
                  { DocumentImageName: this.state.imageName },
                  this.state.activityId,
                  this.state.activityTypeId,
                  PIRetryCount?.retryCount
                );
              }}
              recorder={recorder}
              camera={camera}
              show_RC_back_Button={this.state.show_RC_back_Button}
              show_RC_front_Button={this.state.show_RC_front_Button}
              isOdometerVisible={this.state.isOdometer}
              disableButton={this.state.disableButton}
              titleHn={this.state.titleHn}
              activityId={activityId}
              deleteIcon={deleteIcon}
              tick={tick}
              onDashedRCFrontPress={() => {
                this.setState({ show_RC_front_Button: true });
              }}
              onDashedRCAddMorePress={() => {
                const newAddMoreRCImages = [...this.state.addMoreRCImages];
                newAddMoreRCImages.splice(0, 1);
                this.setState((state) => ({
                  addMoreRCImages: newAddMoreRCImages,
                }));
              }}
              onDashedRCBackPress={() => {
                this.setState({ show_RC_back_Button: true });
              }}
              OnFrontButtonPressed={() => {
                this.setState({ show_RC_front_Button: false });
                if (PIRetryCount?.retryCount == 0) {
                  // for first time
                  this.navigateToCamera_RCB("RCB1");
                } else {
                  // reTry
                  this.navigateToCameraWithRetry_RCB("RCB1");
                }
                firebaseEvents(
                  "RCB1_Capture_Image",
                  { DocumentImageName: this.state.imageName },
                  this.state.activityId,
                  this.state.activityTypeId,
                  PIRetryCount?.retryCount
                );
              }}
              OnBackButtonPressed={() => {
                this.setState({ show_RC_back_Button: false });
                if (PIRetryCount?.retryCount == 0) {
                  // for first time
                  this.navigateToCamera_RCB("RCB2");
                } else {
                  // reTry
                  this.navigateToCameraWithRetry_RCB("RCB2");
                }
                firebaseEvents(
                  "RCB2_Capture_Image",
                  { DocumentImageName: this.state.imageName },
                  this.state.activityId,
                  this.state.activityTypeId,
                  PIRetryCount?.retryCount
                );
              }}
              OnAddMorePressed={async () => {
                count = count + 1;
                this.setState({
                  addMoreRCImages: [...this.state.addMoreRCImages, {}],
                });
                console.log("After increase", count);
                if (PIRetryCount?.retryCount == 0) {
                  var activity = await getCurrentActivity();
                  var rcbCount = activity?.mediaUpload.filter((item) => {
                    return item.imageName.includes("RCB");
                  });
                  var totalRCBLen = rcbCount.length + 1;
                  // for first time
                  this.navigateToCamera_RCB("RCB" + totalRCBLen);
                } else {
                  // reTry
                  this.navigateToCameraWithRetry_RCB("RCB" + count);
                }
                console.log("RCB! >>> ", "RCB" + count);
                firebaseEvents(
                  "AddMore_Capture_Image",
                  { DocumentImageName: this.state.imageName },
                  this.state.activityId,
                  this.state.activityTypeId,
                  PIRetryCount?.retryCount
                );
              }}
              addMoreRCImages={this.state.addMoreRCImages}
              OnSkipPressed={async () => {
                index = index + 1;
                if (PIRetryCount?.retryCount > 0) {
                  // retry

                  if (index >= Retryinstuction.length) {
                    isLast = true;
                  } else {
                    isLast = false;
                  }
                } else {
                  // first try
                  if (index >= instuction.length) {
                    isLast = true;
                  } else {
                    isLast = false;
                  }
                }

                //show next steps and re render the data on screen
                if (PIRetryCount?.retryCount > 0 && isLast) {
                  if (
                    index != 0 &&
                    this.props.RetryImageData.retryImageInfo.length <= 0
                  ) {
                    //  navigate to Progress you screen
                    Orientation.lockToPortrait();
                    var PIclickedCount = await Database.get("PIclickedCount");
                    this.props.navigation.navigate("Progress", {
                      TotalImage: PIclickedCount?.clickedCount,
                    });
                  }
                } else {
                  if (isLast) {
                    if (
                      activityTypeId == "30" ||
                      this.props.RetryImageData.retryImageInfo.length == 0
                    ) {
                      //  navigate to Progress you screen
                      Orientation.lockToPortrait();
                      var PIclickedCount = await Database.get("PIclickedCount");
                      this.props.navigation.navigate("Progress", {
                        TotalImage: PIclickedCount?.clickedCount,
                      });
                    } else {
                      const update = async () => {
                        await Database.update("PIOfflineData", {
                          retryImageData: !!this.props.RetryImageData
                            ? JSON.stringify(this.props.RetryImageData)
                            : "",
                        });
                      };
                      update();
                      this.props.navigation.navigate("InvalidImages", {
                        isLast: isLast,
                      });
                    }
                  }
                }
                this.storeIndex(index);
                this.updateInstructionData();
              }}
              enableAddMore={
                this.state.show_RC_back_Button &&
                this.state.show_RC_front_Button
              }
              activityTypeId={activityTypeId}
            />
            <PhotoTipModal
              isVisible={this.state.isTipModalVisible}
              onBackdropPress={() =>
                this.setState({ isTipModalVisible: false })
              }
              onClose={() => this.setState({ renewalModal: false })}
              onOKPress={() => {
                this.setState({ isTipModalVisible: false });
                this.navigateToCamera(this.state.imageName);
              }}
            />
          </View>
        </SafeAreaView>
      </KeyboardAvoidingView>
    );
  }
}
const styles = StyleSheet.create({
  safeArea: {
    flex: 1,
    backgroundColor: Colors.white,
  },
  main: {
    backgroundColor: "#FFFFFF",
    flex: 1,
  },
  rcTitle: {
    fontFamily: "Muli-Black",
    fontSize: 20,
    marginBottom: 17,
  },
  rcTypeText: {
    fontFamily: "Muli-Bold",
    fontSize: 14,
  },
  tipSubText: {
    fontFamily: "Muli-SemiBold",
    fontSize: 16,
    marginVertical: 16,
    textAlign: "center",
  },
});
const mapReductStateToProps = (reduxState) => {
  const {
    RetryCountData,
    RetryImageData,
    activityData,
    sensorImageData,
    isLastData,
  } = reduxState;
  return {
    RetryCountData,
    RetryImageData,
    activityData,
    sensorImageData,
    isLastData,
  };
};
const mapDispatchToProps = (dispatch) => {
  return {
    retryImageAction: () => dispatch(retryImageAction()),
    retryCountAction: (data) =>
      dispatch({
        type: "RETRY_COUNT",
        payload: data,
      }),
    isLastAction: (data) =>
      dispatch({
        type: "LAST_DATA",
        payload: data,
      }),
    vehicleDetailsAction: (data) =>
      dispatch({
        type: "VEHICLE_DETAILS",
        payload: data,
      }),

    activityDataDetailsAction: (data) =>
      dispatch({
        type: "ACTIVITY_DATA",
        payload: data,
      }),

    sensorDataDetailsAction: (data) =>
      dispatch({
        type: "SENSOR_DETAILS",
        payload: data,
      }),
  };
};

export default connect(mapReductStateToProps, mapDispatchToProps)(PI);
