import React, { Component } from "react";
import {
  Alert,
  FlatList,
  Image,
  PermissionsAndroid,
  StyleSheet,
  Text,
  View,
} from "react-native";
import { instructionData } from "./common/Services/instruction";
import {
  SCREEN_WIDTH,
  SCREEN_HEIGHT,
  VIDEO_TITLE,
  VIDEO_TITLE_HN,
  RC_BOOK,
  RC_BOOK_HN,
  WEB_REQUEST,
  ANDROID_REQUEST,
  CNG,
  CNG_HN,
  PUC_Hn,
  PUC,
  ODOMETER,
  ODOMETER_HN,
} from "./common/Constants";
import Header from "./Screens/Header";
import VehicleSurveyInstruction from "./Screens/VehicleSurveyInstruction";
import Orientation from "react-native-orientation";
import {
  PrimaryButton,
  DashedButton,
  Spinner,
} from "./common/ThemedComponents";
import { translate } from "./common/localize/i18n";
import { connect } from "react-redux";
import { ScrollView, TouchableOpacity } from "react-native-gesture-handler";
import Modal from "./common/Modal";
import Database from "../../../Components/common/Database";
import reactotron from "reactotron-react-native";
import Geolocation from "react-native-geolocation-service";
import { startCapturingSensorData } from "./common/SensorData";
import { measureConnectionSpeed } from "react-native-network-bandwith-speed";
import { retryImageAction } from "./redux/actions/retryImageAction";
import { async } from "validate.js";
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");

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

let realm = Database.getRealm();
var RealmData = realm.objects("SelectedLang");
var PIRetryCount = realm.objects("PIRetryCount");

var RCBCountInRetry;
var activityId, activityTypeId, licensePlateNumber, quoteNumber;
var DataSpeed;

var RealmInstructionData = realm.objects("PIVechicleInstruction");
var RealmRetryInstructionData = realm.objects("PIOfflineData");
var vechicleData = realm.objects("PIVechicleData");
var PIStartOver = realm.objects("PIStartOver");
var realmIndex = realm.objects("PIINDEX");
class PI extends Component {
  constructor(props) {
    // this is for from where we should start
    if (PIStartOver[0]?.isStartOver) {
      // if (true) {
      console.log(
        "********************** Let's Start from Begining ******************************"
      );
      index = 0;
    } else {
      console.log(
        "************************ Let's Start from Where We Left ***********************",
        realmIndex[0]?.lastIndex
      );
      index =
        realmIndex[0]?.lastIndex == "undefined" || realmIndex[0]?.lastIndex <= 0
          ? 0
          : realmIndex[0]?.lastIndex - 1;
    }

    super(props);
    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,
    };
  }

  componentWillUnmount() {
    this.unsubscribe();
  }

  componentDidMount() {
    startCapturingSensorData();
    Orientation.lockToLandscapeLeft();
    this.unsubscribe = this.props.navigation.addListener("focus", () => {
      try {
        Orientation.lockToLandscapeLeft();
        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 = realm.objects("PIVechicleData");
          activityId = PIVechicleData[0]?.activityId;
          activityTypeId = PIVechicleData[0]?.activityTypeId;
          licensePlateNumber = PIVechicleData[0]?.licensePlateNumber;
          quoteNumber = PIVechicleData[0]?.quoteNumber;
        }
        this.props.vehicleDetailsAction({
          activityID: activityId,
          activityTypeId: activityTypeId,
          licensePlateNumber: licensePlateNumber,
          quoteNumber: quoteNumber,
        });
        isLast = false;
        //  call retry logic
        if (PIRetryCount[0]?.retryCount > 0) {
          if (PIRetryCount[0]?.isAddNewImageData) {
            // if(true){
            // if(true)
            // {
            index = 0;
            Retryinstuction = JSON.parse(
              RealmRetryInstructionData[0].retryImageData
            ).retryImageInfo;

            console.log("Before clear data >>> ", this.props.RetryImageData);
            // this.props.retryImageAction();
            console.log("After Clear Data >>> ", this.props.RetryImageData);

            this.updateRetryInstruction();
          }
        } else {
          // frist try
          // this.callInstructionServices();
          instuction = [];
          instuction = JSON.parse(RealmInstructionData[0]?.instuction);
          this.setState({ isLoading: false });
          this.updateInstructionData();
        }
      } catch (error) {
        console.log("Error in DidM in PI ", error);
      }
    });
  }

  updateRetryInstruction = () => {
    try {
      console.log("$$$$$$$$$$$$$$$", Retryinstuction.length, 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;
      if (PIRetryCount[0]?.isAddNewImageData) {
        // for checking RCB is uploaded of not
        Retryinstuction.filter((item) => {
          if (item?.imageName?.includes("RCB1")) {
            this.setState({ show_RC_front_Button: true });
          }
          if (item?.imageName?.includes("RCB2")) {
            this.setState({ show_RC_back_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[0]?.retryCount,
          index: PIRetryCount[0]?.index,
          isAddNewImageData: false,
        });

        var realmRetryCount = PIRetryCount[0]?.retryCount;
        var realmRetryIndex = PIRetryCount[0]?.index;
        realm.write(() => {
          realm.delete(realm.objects("PIRetryCount"));
          realm.create("PIRetryCount", {
            retryCount: realmRetryCount,
            index: realmRetryIndex,
            isAddNewImageData: false,
          });
        });
      }
      if (index < Retryinstuction?.length) {
        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: Retryinstuction.length,
        });
      }
    } catch (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 {
        let requestTypeName = this.instructionWebOrAndroid(activityTypeId);
        let requestTypeValue;
        if (requestTypeName == WEB_REQUEST) {
          requestTypeValue = 1;
        } else {
          requestTypeValue = 0;
        }
        let V_instuction = await instructionData({
          typeId: activityTypeId,
          requestValue: requestTypeValue,
        });

        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();
        this.setState({ isLoading: false });
      } catch (error) {
        this.setState({ isLoading: true });
      }
    }
  };
  //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
  navigateToCameraWithRetry_RCB(docName) {
    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[0]?.retryCount, // using in preview screen for start capturing the sensor data
      licensePlateNumber: licensePlateNumber,
      activityTypeId: activityTypeId,
      activityId: activityId,
    });
    this.updateRetryInstruction();
    return 0;
  }
  // For RCB
  navigateToCamera_RCB(docName) {
    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[0]?.retryCount, // using in preview screen for start capturing the sensor data
      licensePlateNumber: licensePlateNumber,
      activityTypeId: activityTypeId,
      activityId: activityId,
    });
    this.updateInstructionData();
    return 0;
  }
  // open camera
  navigateToCamera(docName) {
    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: instuction[index]?.imageName,

      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[0]?.retryCount, // using in preview screen for start capturing the sensor data
      licensePlateNumber: licensePlateNumber,
      activityTypeId: activityTypeId,
      activityId: activityId,
    });
    if (
      instuction[index]?.stepTitle == RC_BOOK ||
      instuction[index]?.stepTitleHn == RC_BOOK_HN
    ) {
      index = index;
    } else {
      index = index + 1;
    }
    this.updateInstructionData();
    return 0;
  }
  // open camera with retry
  navigateToCameraWithRetry(docName) {
    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[0]?.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;
  }
  // photo tip modal
  photoTipUx = () => {
    return (
      <ScrollView>
        <View
          style={{
            flex: 1,
            marginLeft: 24,
            marginRight: 24,
            marginTop: SCREEN_HEIGHT / 18,
          }}
        >
          <View style={{ flex: 0.8 }}>
            <Image
              source={cameraTip}
              style={{
                width: SCREEN_WIDTH - 78,
                height: SCREEN_WIDTH / 2.5,
                resizeMode: "contain",
                marginLeft: 10,
                marginRight: 10,
                alignSelf: "center",
              }}
            />
          </View>
          <View style={{ flex: 0.2 }}>
            <Text style={styles.tipSubText}>
              {translate(
                "Hold the phone horizontally for capturing better photos of the vehicle"
              )}
            </Text>
            <PrimaryButton
              style={{ marginTop: 24 }}
              onPress={() => {
                this.setState({ isTipModalVisible: false });
                this.navigateToCamera(this.state.imageName);
              }}
            >
              {translate("Ok, Got it")}
            </PrimaryButton>
          </View>
        </View>
      </ScrollView>
    );
  };
  //Photo tip Modal
  photoTipModal = () => {
    return (
      <View>
        <Modal
          isVisible={this.state.isTipModalVisible}
          onBackdropPress={() => this.setState({ isTipModalVisible: false })}
          onClose={() => this.setState({ renewalModal: false })}
          heading={"Photo Tip"}
          isTranslate={true}
        >
          {this.photoTipUx()}
        </Modal>
      </View>
    );
  };
  // For Proceed/capture /capture video
  onButtonPress = () => {
    // for first time instruction
    try {
      console.log(
        "!!!!!!!!!!!",
        index,
        instuction.length,
        PIRetryCount[0]?.retryCount
      );
      if (index <= instuction.length && PIRetryCount[0]?.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[0]?.retryCount > 2 && isLast) {
            if (
              isLast &&
              index != 0 &&
              this.props.RetryImageData.retryImageInfo.length <= 0
            ) {
              //  navigate to Progress you screen
              Orientation.lockToPortrait();
              this.props.navigation.navigate("Progress");
            }
          } else {
            console.log("is Last  >> ", isLast);
            if (isLast) {
              if (
                activityTypeId == "30" ||
                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();
                  this.props.navigation.navigate("Progress");
                }
              } else {
                if (this.props.RetryImageData.retryImageInfo.length > 0) {
                  // "this.props.RetryImageData.retryImageInfo.length" this insted of "Retryinstuction?.length"  becouse require updated data here.
                  realm.write(() => {
                    realm.delete(realm.objects("PIOfflineData"));
                    realm.create("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 = (index) => {
    realm.write(() => {
      realm.delete(realm.objects("PIINDEX"));
      realm.create("PIINDEX", {
        lastIndex: index,
      });
    });
  };
  render() {
    // Orientation.lockToLandscapeLeft();
    return (
      <View style={styles.main}>
        <Spinner loading={false} />
        <Header
          currentStep={index}
          totalSteps={this.state.totalSteps}
          showSteps={true}
          onbackPress={() => {
            // first flow
            if (
              index < instuction.length &&
              PIRetryCount[0]?.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();
          }}
        ></Header>
        {/* Instructions */}
        <VehicleSurveyInstruction
          title={
            RealmData[0]?.PreferredLanguage == "en"
              ? this.state.title
              : this.state.titleHn
          }
          subTitle={
            RealmData[0]?.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) {
              this.setState({ disableButton: false });
            } else {
              this.setState({ disableButton: true });
            }

            console.log("ODOMETER READING IN PI", value.length);
          }}
          DocumentName={this.state.imageName}
          onCaptureButton={() => {
            this.onButtonPress();
          }}
          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[0]?.retryCount == 0) {
              // for first time
              this.navigateToCamera_RCB("RCB1");
            } else {
              // reTry
              this.navigateToCameraWithRetry_RCB("RCB1");
            }
          }}
          OnBackButtonPressed={() => {
            this.setState({ show_RC_back_Button: false });
            if (PIRetryCount[0]?.retryCount == 0) {
              // for first time
              this.navigateToCamera_RCB("RCB2");
            } else {
              // reTry
              this.navigateToCameraWithRetry_RCB("RCB2");
            }
          }}
          OnAddMorePressed={() => {
            this.setState({
              addMoreRCImages: [...this.state.addMoreRCImages, {}],
            });
            if (PIRetryCount[0]?.retryCount == 0) {
              // for first time
              this.navigateToCamera_RCB("RCB2");
            } else {
              // reTry
              this.navigateToCameraWithRetry_RCB("RCB2");
            }
          }}
          addMoreRCImages={this.state.addMoreRCImages}
          OnSkipPressed={() => {
            index = index + 1;
            if (PIRetryCount[0]?.retryCount > 2) {
              // 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[0]?.retryCount > 2 && isLast) {
              if (
                index != 0 &&
                this.props.RetryImageData.retryImageInfo.length <= 0
              ) {
                //  navigate to Progress you screen
                Orientation.lockToPortrait();
                this.props.navigation.navigate("Progress");
              }
            } else {
              if (isLast) {
                if (
                  activityTypeId == "30" ||
                  this.props.RetryImageData.retryImageInfo.length == 0
                ) {
                  //  navigate to Progress you screen
                  Orientation.lockToPortrait();
                  this.props.navigation.navigate("Progress");
                } else {
                  realm.write(() => {
                    realm.delete(realm.objects("PIOfflineData"));
                    realm.create("PIOfflineData", {
                      retryImageData: !!this.props.RetryImageData
                        ? JSON.stringify(this.props.RetryImageData)
                        : "",
                    });
                  });
                  this.props.navigation.navigate("InvalidImages", {
                    isLast: isLast,
                  });
                }
              }
            }
            this.storeIndex(index);
            this.updateInstructionData();
          }}
        />
        {this.photoTipModal()}
      </View>
    );
  }
}
const styles = StyleSheet.create({
  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,
    marginTop: 24,
    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,
      }),
  };
};

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