import React, {
  forwardRef,
  useEffect,
  useReducer,
  useRef,
  useState,
} from "react";
import {
  Text,
  TouchableOpacity,
  StyleSheet,
  View,
  Image,
  Alert,
  Switch,
} from "react-native";
import { async } from "validate.js";
import Colors from "../common/Colors";
import { SCREEN_HEIGHT, SCREEN_WIDTH } from "../common/Constants";
import Database from "../../../../Components/common/Database";
import { PrimaryButton, TextInput } from "../common/ThemedComponents";
import Orientation from "react-native-orientation";
import AnimationEaseLinear from "./AnimationEaseLinear";
import ViewShot, { captureRef } from "react-native-view-shot";
import UploadFile from "react-native-digitcamera/src/Screens/UploadFile";
import Modal from "../common/Modal";
import InstructionsScreen from "./InstructionsScreen";
import Icon from "react-native-vector-icons/dist/FontAwesome";
import MIcon from "react-native-vector-icons/MaterialIcons";
import Steps from "react-native-digitcamera/src/Screens/Steps";
import style from "../../../../Components/common/CommonStyle";
import KeepAwake from "react-native-keep-awake";

import { useSelector, useDispatch } from "react-redux";
import {
  UELogEvent,
  UELogMessage,
} from "../common/libEventLog/UserExperior/LibUserExperior";
export const zIndex_main_view = 100,
  zIndex_image_instruction = 125,
  zIndex_snapshot_preview_image = 150,
  zIndex_moving_thumbnail = 250,
  zIndex_bottom_instruction = 300,
  zIndex_stop_recording = 325,
  zIndex_start_recording = 400,
  zIndex_flash_torch = 124,
  zIndex_flash_torchVDO = 326;
zIndex_steps_instruction = 312;

const RCB1 = "RCB1",
  RCB2 = "RCB2",
  DBD = "DBD",
  VDO = "VDO";

export var sensorImageDetails = [];

export const NO_OF_POSES = 13; // 1 is width of thumbnail itself
const STEP_INSTRUCTION_COUNT = 19;
export const OBJ_WIDTH = SCREEN_HEIGHT / NO_OF_POSES;
const newPosePeriod = SCREEN_HEIGHT / NO_OF_POSES;
export const ANIMATION_TRACK = SCREEN_HEIGHT + SCREEN_HEIGHT * 0.1;
export const ANIM_DURATION = 2 * 60 * 1000 + 10 * 1000; // 10 sec extra
// export const ANIM_DURATION = 2 * 6 * 1000 + 1 * 1000; // 10 sec extra
const EXTRA_TIME = 1 * 60 * 1000;
const HOLD_ON_TIME = 5000;
export const DURATION_PERIOD = ANIM_DURATION / NO_OF_POSES; // 19 is the no. of instructions coming from back end
export const DURATION_PERIOD_ARR = [
  DURATION_PERIOD / 2,
  DURATION_PERIOD / 2,
  DURATION_PERIOD / 2,
  DURATION_PERIOD / 2,
  DURATION_PERIOD / 2,
  DURATION_PERIOD / 2,
  DURATION_PERIOD,
  DURATION_PERIOD / 3,
  DURATION_PERIOD / 3,
  DURATION_PERIOD / 3,
  DURATION_PERIOD,
  DURATION_PERIOD,
  DURATION_PERIOD,
  DURATION_PERIOD,
  DURATION_PERIOD,
  DURATION_PERIOD,
  DURATION_PERIOD,
  DURATION_PERIOD / 2,
  DURATION_PERIOD / 2,
];
const PAUSE_PART_NAME = "engine bay";

var locationRetryCount = 0;
let realm = Database.getRealm();
var instructionInDb = realm.objects("PIVechicleInstruction");
var PIRetryCount = realm.objects("PIRetryCount");
var PIVechicleData = realm.objects("PIVechicleData");

var pause = false;
var animValue = 0;
export const StencilAnimation = forwardRef((props, cameraRef) => {
  // const [pause, setPause] = useState(false)
  const [easeAnimation, setEaseAnimation] = useState(false);
  const [startRecording, setStartRecording] = useState(false);
  const [disableStopVideoButton, setDisableStopVideoButton] = useState(true);
  var [currentLatitude, setCurrentLatitude] = useState("");
  var [currentLongitude, setCurrentLongitude] = useState("");
  const [imagePreview, setImagePreview] = useState(false);
  const [imagePreviewUri, setImagePreviewUri] = useState("");
  const [dateTime, setDateTime] = useState("");
  const [odometerReadings, setOdometerReadings] = useState("");
  const [isMoreRCB, setIsMoreRCB] = useState(false);
  const [instructionsModalVisible, setInstructionsModalVisible] =
    useState(false);
  const viewShotRef = useRef();
  const dispatch = useDispatch();

  // const [enableRCBPreview, setEnableRCBPreview] = useState(false);

  var dbInstr = instructionInDb[0]?.instuction;
  // if (__DEV__ && (dbInstr === undefined || dbInstr.length <= 0)) {
  // //   console.log("**** dbInstruction not available taking hard coded");
  //dbInstr = JSON.parse('[{\"surveyStepsId\":1053,\"createdDate\":\"Feb 21, 2020 12:15:05 PM\",\"isLast\":false,\"lastModifiedDate\":\"Feb 21, 2020 12:15:05 PM\",\"stepAssests\":\"https://cdn.godigit.com/digitEdgeAssets/Motor/4W_PI_RCB1_V2.jpg\",\"stepStencilAssests\":\"\",\"stepTitle\":\"RC Book/Card\",\"stepTitleHn\":\"आरसी बुक/कार्ड\",\"imageName\":\"RCB1\",\"displayOrder\":160,\"type\":\"image\",\"TSurveyInstructions\":[{\"surveyInstructionsId\":1740,\"createdDate\":\"May 18, 2022 12:25:18 PM\",\"instructionData\":\"Take a picture of the front of your RC book/card.\",\"lastModifiedDate\":\"May 18, 2022 12:25:18 PM\",\"instructionTime\":1,\"instructionDataHn\":\"अपनी आरसी बुक/कार्ड के सामने की तस्वीर लें।\",\"displayOrder\":1,\"type\":\"\",\"effectiveDate\":\"May 18, 2022 12:27:19 PM\"}],\"effectiveDate\":\"Dec 17, 2022 03:18:48 PM\"},{\"surveyStepsId\":1056,\"createdDate\":\"Feb 21, 2020 12:15:05 PM\",\"isLast\":false,\"lastModifiedDate\":\"Feb 21, 2020 12:15:05 PM\",\"stepAssests\":\"https://cdn.godigit.com/digitEdgeAssets/Motor/4W_PI_RCB2_V2.jpg\",\"stepStencilAssests\":\"\",\"stepTitle\":\"RC Book/Card\",\"stepTitleHn\":\"आरसी बुक/कार्ड\",\"imageName\":\"RCB2\",\"displayOrder\":180,\"type\":\"image\",\"TSurveyInstructions\":[{\"surveyInstructionsId\":1741,\"createdDate\":\"May 18, 2022 12:25:18 PM\",\"instructionData\":\"Take a picture of the back of your RC book/card.\",\"lastModifiedDate\":\"May 18, 2022 12:25:18 PM\",\"instructionTime\":2,\"instructionDataHn\":\"अपनी आरसी बुक/कार्ड के पीछे की तस्वीर लें।\",\"displayOrder\":2,\"type\":\"\",\"effectiveDate\":\"May 18, 2022 12:27:19 PM\"}],\"effectiveDate\":\"Dec 17, 2022 03:18:48 PM\"},{\"surveyStepsId\":1054,\"createdDate\":\"Feb 21, 2020 12:15:05 PM\",\"description\":\"<b>Note:</b> Odometer reading indicates the <b>total distance the vehicle has travelled!</b> Please ensure the reading reflects that and is not set to display trip reading.\",\"isLast\":false,\"descriptionHn\":\"सुनिश्चित करें कि ओडोमीटर किमी रीडिंग लेते समय इंजन चालू है\",\"lastModifiedDate\":\"Feb 21, 2020 12:15:05 PM\",\"stepAssests\":\"https://cdn.godigit.com/digitEdgeAssets/Motor/MZBG2T7_Odometer-01_V2.jpg\",\"stepStencilAssests\":\"\",\"stepTitle\":\"Please enter the odometer km reading\",\"stepTitleHn\":\"कृपया ओडोमीटर किमी रीडिंग दर्ज करें\",\"imageName\":\"DBD\",\"displayOrder\":205,\"type\":\"input\",\"TSurveyInstructions\":[],\"effectiveDate\":\"Dec 17, 2022 03:18:48 PM\"},{\"surveyStepsId\":1055,\"createdDate\":\"Feb 21, 2020 12:15:05 PM\",\"description\":\"Shoot video from a distance to capture the entire vehicle\",\"isLast\":false,\"descriptionHn\":\"पूरीगाड़ी को फ़ोकस करने के लिए दूर से वीडियो शूट करें\",\"lastModifiedDate\":\"Feb 21, 2020 12:15:05 PM\",\"stepAssests\":\"https://d2h44aw7l5xdvz.cloudfront.net/videos/self-inspection-for-car.mp4\",\"stepStencilAssests\":\"\",\"stepTitle\":\"Take a 360° video\",\"stepTitleHn\":\"360 ° वीडियो लें \\\"\",\"imageName\":\"VDO\",\"displayOrder\":220,\"type\":\"video\",\"TSurveyInstructions\":[{\"surveyInstructionsId\":1742,\"createdDate\":\"May 18, 2022 12:30:48 PM\",\"instructionData\":\"We will record inside the engine bay so make sure the bonnet is kept open.\",\"lastModifiedDate\":\"May 18, 2022 12:30:48 PM\",\"instructionTime\":3,\"instructionDataHn\":\"हम इंजन बे के अंदर रिकॉर्ड करेंगे इसलिए सुनिश्चित करें कि बोनट खुला रखा गया है\",\"displayOrder\":3,\"type\":\"image\",\"effectiveDate\":\"May 18, 2022 12:32:26 PM\",\"instructionTitle\":\"Please open the bonnet of the car\",\"okButtonText\":\"I have opened the bonnet\",\"instructionAssests\":\"https://d2h44aw7l5xdvz.cloudfront.net/CRM/PRM/open_bonnet.png\"},{\"surveyInstructionsId\":1743,\"createdDate\":\"May 18, 2022 12:30:48 PM\",\"instructionData\":\"The engine should be ON throughout the inspection.\",\"lastModifiedDate\":\"May 18, 2022 12:30:48 PM\",\"instructionTime\":3,\"instructionDataHn\":\"पूरे निरीक्षण के दौरान इंजन चालू रहना चाहिए\",\"displayOrder\":4,\"type\":\"image\",\"effectiveDate\":\"May 18, 2022 12:32:26 PM\",\"instructionTitle\":\"Start your vehicle\",\"okButtonText\":\"I have started the vehicle\",\"instructionAssests\":\"https://d2h44aw7l5xdvz.cloudfront.net/CRM/PRM/key_start.png\"},{\"surveyInstructionsId\":1744,\"createdDate\":\"May 18, 2022 12:30:48 PM\",\"instructionData\":\"Take some time & locate your chassis number. Please make sure you find the <b>embossed chassis number</b>& not the sticker.\",\"lastModifiedDate\":\"May 18, 2022 12:30:48 PM\",\"instructionTime\":3,\"instructionDataHn\":\"कुछ समय निकालें और अपना चेसिस नंबर खोजें\",\"displayOrder\":5,\"type\":\"image\",\"effectiveDate\":\"May 18, 2022 12:32:26 PM\",\"instructionTitle\":\"Find your chassis number\",\"okButtonText\":\"I have found the chassis no.\",\"instructionAssests\":\"https://d2h44aw7l5xdvz.cloudfront.net/CRM/PRM/chassis_find.png\"},{\"surveyInstructionsId\":1745,\"createdDate\":\"May 31, 2022 02:40:44 PM\",\"instructionData\":\"What is embossed chassis no.?\",\"lastModifiedDate\":\"May 31, 2022 02:40:44 PM\",\"instructionTime\":2,\"displayOrder\":6,\"type\":\"image\",\"effectiveDate\":\"May 31, 2022 02:40:44 PM\",\"instructionTitle\":\"What is embossed chassis no.?\"},{\"surveyInstructionsId\":1746,\"createdDate\":\"May 31, 2022 02:40:44 PM\",\"instructionData\":\"What is embossed chassis no.?\",\"lastModifiedDate\":\"May 31, 2022 02:40:44 PM\",\"instructionTime\":2,\"displayOrder\":7,\"type\":\"image\",\"effectiveDate\":\"May 31, 2022 02:40:44 PM\",\"instructionTitle\":\"What is embossed chassis no.?\"},{\"surveyInstructionsId\":1747,\"createdDate\":\"May 31, 2022 02:40:44 PM\",\"instructionData\":\"Make sure the <b>chassis number</b> is visible on the screen\",\"lastModifiedDate\":\"May 31, 2022 02:40:44 PM\",\"instructionTime\":2,\"displayOrder\":8,\"type\":\"instruction\",\"effectiveDate\":\"May 31, 2022 02:40:44 PM\",\"instructionTitle\":\"\"},{\"surveyInstructionsId\":1748,\"createdDate\":\"May 31, 2022 02:40:44 PM\",\"instructionData\":\"Make sure all the <b>doors are closed</b>\",\"lastModifiedDate\":\"May 31, 2022 02:40:44 PM\",\"instructionTime\":2,\"displayOrder\":9,\"type\":\"instruction\",\"effectiveDate\":\"May 31, 2022 02:40:44 PM\",\"instructionTitle\":\"\"},{\"surveyInstructionsId\":1749,\"createdDate\":\"May 31, 2022 02:40:44 PM\",\"instructionData\":\"Face the <b>front of the car</b>\",\"lastModifiedDate\":\"May 31, 2022 02:40:44 PM\",\"instructionTime\":2,\"displayOrder\":10,\"type\":\"instruction\",\"effectiveDate\":\"May 31, 2022 02:40:44 PM\",\"instructionTitle\":\"\"},{\"surveyInstructionsId\":1750,\"createdDate\":\"May 31, 2022 02:40:44 PM\",\"instructionData\":\"Let’s look inside the <b>engine bay</b>\",\"lastModifiedDate\":\"May 31, 2022 02:40:44 PM\",\"instructionTime\":2,\"displayOrder\":11,\"type\":\"instruction\",\"effectiveDate\":\"May 31, 2022 02:40:44 PM\",\"instructionTitle\":\"\"},{\"surveyInstructionsId\":1751,\"createdDate\":\"May 31, 2022 02:40:44 PM\",\"instructionData\":\"Face the <b>front of the car</b>\",\"lastModifiedDate\":\"May 31, 2022 02:40:44 PM\",\"instructionTime\":2,\"displayOrder\":12,\"type\":\"instruction\",\"effectiveDate\":\"May 31, 2022 02:40:44 PM\",\"instructionTitle\":\"\"},{\"surveyInstructionsId\":1752,\"createdDate\":\"May 31, 2022 02:40:44 PM\",\"instructionData\":\"<b>Number plate & front windshield</b> should be visible\",\"lastModifiedDate\":\"May 31, 2022 02:40:44 PM\",\"instructionTime\":2,\"displayOrder\":13,\"type\":\"instruction\",\"effectiveDate\":\"May 31, 2022 02:40:44 PM\",\"instructionTitle\":\"\"},{\"surveyInstructionsId\":1753,\"createdDate\":\"May 31, 2022 02:40:44 PM\",\"instructionData\":\"Move towards the front <b>passenger side</b>\",\"lastModifiedDate\":\"May 31, 2022 02:40:44 PM\",\"instructionTime\":2,\"displayOrder\":14,\"type\":\"instruction\",\"effectiveDate\":\"May 31, 2022 02:40:44 PM\",\"instructionTitle\":\"\"},{\"surveyInstructionsId\":1754,\"createdDate\":\"May 31, 2022 02:40:44 PM\",\"instructionData\":\"Ensure the full car is in the frame\",\"lastModifiedDate\":\"May 31, 2022 02:40:44 PM\",\"instructionTime\":2,\"displayOrder\":15,\"type\":\"instruction\",\"effectiveDate\":\"May 31, 2022 02:40:44 PM\",\"instructionTitle\":\"\"},{\"surveyInstructionsId\":1755,\"createdDate\":\"May 31, 2022 02:40:44 PM\",\"instructionData\":\"Complete side of the car should be seen\",\"lastModifiedDate\":\"May 31, 2022 02:40:44 PM\",\"instructionTime\":2,\"displayOrder\":16,\"type\":\"instruction\",\"effectiveDate\":\"May 31, 2022 02:40:44 PM\",\"instructionTitle\":\"\"},{\"surveyInstructionsId\":1756,\"createdDate\":\"May 31, 2022 02:40:44 PM\",\"instructionData\":\"Step back if you need to fit the car in the frame\",\"lastModifiedDate\":\"May 31, 2022 02:40:44 PM\",\"instructionTime\":2,\"displayOrder\":17,\"type\":\"instruction\",\"effectiveDate\":\"May 31, 2022 02:40:44 PM\",\"instructionTitle\":\"\"},{\"surveyInstructionsId\":1757,\"createdDate\":\"May 31, 2022 02:40:44 PM\",\"instructionData\":\"Move to the <b>back of the car</b>\",\"lastModifiedDate\":\"May 31, 2022 02:40:44 PM\",\"instructionTime\":2,\"displayOrder\":18,\"type\":\"instruction\",\"effectiveDate\":\"May 31, 2022 02:40:44 PM\",\"instructionTitle\":\"\"},{\"surveyInstructionsId\":1758,\"createdDate\":\"May 31, 2022 02:40:44 PM\",\"instructionData\":\"<b>Number plate & back windshield</b> should be visible\",\"lastModifiedDate\":\"May 31, 2022 02:40:44 PM\",\"instructionTime\":2,\"displayOrder\":19,\"type\":\"instruction\",\"effectiveDate\":\"May 31, 2022 02:40:44 PM\",\"instructionTitle\":\"\"},{\"surveyInstructionsId\":1759,\"createdDate\":\"May 31, 2022 02:40:44 PM\",\"instructionData\":\"Move to the <b>driver’s side</b>\",\"lastModifiedDate\":\"May 31, 2022 02:40:44 PM\",\"instructionTime\":2,\"displayOrder\":20,\"type\":\"instruction\",\"effectiveDate\":\"May 31, 2022 02:40:44 PM\",\"instructionTitle\":\"\"},{\"surveyInstructionsId\":1760,\"createdDate\":\"May 31, 2022 02:40:44 PM\",\"instructionData\":\"Complete side of the car should be visible\",\"lastModifiedDate\":\"May 31, 2022 02:40:44 PM\",\"instructionTime\":2,\"displayOrder\":21,\"type\":\"instruction\",\"effectiveDate\":\"May 31, 2022 02:40:44 PM\",\"instructionTitle\":\"\"},{\"surveyInstructionsId\":1761,\"createdDate\":\"May 31, 2022 02:40:44 PM\",\"instructionData\":\"Move to the <b>front of the car</b>\",\"lastModifiedDate\":\"May 31, 2022 02:40:44 PM\",\"instructionTime\":2,\"displayOrder\":22,\"type\":\"instruction\",\"effectiveDate\":\"May 31, 2022 02:40:44 PM\",\"instructionTitle\":\"\"},{\"surveyInstructionsId\":1762,\"createdDate\":\"May 31, 2022 02:40:44 PM\",\"instructionData\":\"Move closer to the <b>windshield</b>\",\"lastModifiedDate\":\"May 31, 2022 02:40:44 PM\",\"instructionTime\":2,\"displayOrder\":23,\"type\":\"instruction\",\"effectiveDate\":\"May 31, 2022 02:40:44 PM\",\"instructionTitle\":\"\"},{\"surveyInstructionsId\":1763,\"createdDate\":\"May 31, 2022 02:40:44 PM\",\"instructionData\":\"Please sit on the <b>drivers seat</b>\",\"lastModifiedDate\":\"May 31, 2022 02:40:44 PM\",\"instructionTime\":2,\"displayOrder\":24,\"type\":\"instruction\",\"effectiveDate\":\"May 31, 2022 02:40:44 PM\",\"instructionTitle\":\"\"},{\"surveyInstructionsId\":1764,\"createdDate\":\"May 31, 2022 02:40:44 PM\",\"instructionData\":\"All corners of the <b>windshield</b> should be filmed from inside\",\"lastModifiedDate\":\"May 31, 2022 02:40:44 PM\",\"instructionTime\":2,\"displayOrder\":25,\"type\":\"instruction\",\"effectiveDate\":\"May 31, 2022 02:40:44 PM\",\"instructionTitle\":\"\"},{\"surveyInstructionsId\":1765,\"createdDate\":\"May 31, 2022 02:40:44 PM\",\"instructionData\":\"Let’s take a look at the <b>odometer</b>\",\"lastModifiedDate\":\"May 31, 2022 02:40:44 PM\",\"instructionTime\":2,\"displayOrder\":26,\"type\":\"instruction\",\"effectiveDate\":\"May 31, 2022 02:40:44 PM\",\"instructionTitle\":\"\"}],\"effectiveDate\":\"Dec 17, 2022 03:18:48 PM\"}]');
  // } else {
  if (dbInstr !== undefined) {
    /*
    * For some reason StencilAnimation rerenders
    * so on thank you screen, instructions are deleted from realm
    *  and in StencilAnimation dbInstr is undefined
    *  so I have added the check so that app wont crash
    */
    dbInstr = JSON.parse(dbInstr);
  }
  // }
  var [instructionArr, setInstructionArr] = useState(dbInstr);
  const originalState = instructionArr[0];
  const [instructionManager, moveToNextStencil] = useReducer(
    reducer,
    originalState
  );
  /*torch mode*/
  var posePeriodInterval = useRef();
  var animObjRef = useRef();
  var animatedRef = useRef();
  var timeoutRef = useRef();
  var resumeTimerRef = useRef();
  var pauseTimerRef = useRef();
  var extraTimeRef = useRef();
  var nextStepRef = useRef();
  var prevStepRef = useRef();
  var resetStepRef = useRef();

  function reducer(state = originalState, action) {
    let newState;
    switch (action.type) {
      case "init":
        console.log("***** reducer init: ");
        newState = instructionArr[0];
        break;
      case "next":
        const oldIndex = instructionArr.findIndex(
          (obj) => obj.displayOrder === state.displayOrder
        );
        const nextIndex = oldIndex + 1;
        console.log("***** reducer next " + nextIndex);
        const newInstruction = instructionArr[nextIndex];
        newState = newInstruction;
        break;
      case "prev":
        const oldPrevIndex = instructionArr.findIndex(
          (obj) => obj.displayOrder === state.displayOrder
        );
        const nextPrevIndex = oldPrevIndex - 1;
        console.log("***** reducer prev " + nextPrevIndex);
        newState = instructionArr[nextPrevIndex];
        break;
      case "toImageName" /* @NEWORDER */:
        const newInstructions = instructionArr.find(
          (item) => item.imageName === action.payload
        );
        newState = newInstructions;
        break;
    }
    console.log("**** reducer returns: " + newState.imageName);
    return newState;
  }
  useEffect(() => {
    getLatLong();
    getTime();
  }, [instructionManager]);

  /*@NEWORDER*/
  /* Getting RCB data from redux to handle RCB Cases */
  const RCBDATA = useSelector((state) => state.rcbPreviewData);
  /* currentImage represents what photo is being taken, is it Front, Back or Other Pages. */
  const currentImage = RCBDATA.currentImage;

  /* Getting length of the extra images */
  const MoreRCBImages = RCBDATA.rcbPreviewData.filter(
    (item) => item.info === "RC More Pages"
  );

  useEffect(() => {
    Orientation.lockToLandscapeLeft();
    KeepAwake.activate();
    const myFun = async () => {
      await getInstructionsFromDb();
    };
    myFun();
    return () => {
      KeepAwake.deactivate();
    };
  }, []);

  const animationListener = (anim, value) => {
    if (animObjRef.current === undefined) {
      animObjRef.current = anim;
    }
    animValue = value;
  };

  const posePeriodIntervalFun = () => {
    const totalInstr = DURATION_PERIOD_ARR.length;
    var count = 0;
    const call = (duration) => {
      if (count < totalInstr) {
        const timer = setTimeout(() => {
          clearTimeout(timer);
          // console.log("*** posePeriodIntervalFun count: "+count+" duration: "+duration);
          if (nextStepRef.current && !pause) {
            moveSteps(count);
            count += 1;
          }
          call(DURATION_PERIOD_ARR[count]);
        }, duration);
      }
    };
    call(DURATION_PERIOD_ARR[count]);

    // posePeriodInterval.current = setInterval(() => {
    const moveSteps = (count) => {
      console.log("**** moveSteps to count: " + count);
      // nextStencil();
      // if (nextStepRef.current && !pause) {
      const stepManager = nextStepRef.current();
      if (
        stepManager !== undefined &&
        stepManager?.instructionData.indexOf(PAUSE_PART_NAME) >= 0
      ) {
        // setPause(true)
        if (animatedRef.current != undefined) {
          animatedRef.current[0].stop();
        }
        if (pauseTimerRef.current != undefined) {
          pauseTimerRef.current();
        }
        pause = true;
        Alert.alert("Close the bonnet", "I have closed the bonnet", [
          {
            text: "Let's Continue",
            onPress: () => {
              // setPause(false)
              if (resumeTimerRef.current != undefined) {
                resumeTimerRef.current();
              }
              pause = false;
              console.log("*** StencilAnimation waiting for chassis");
              animObjRef.current.setValue(animValue);
              if (animatedRef.current != undefined) {
                animatedRef.current[0].start(() => {
                  const dontKnowWhy = setTimeout(() => {
                    clearTimeout(dontKnowWhy);
                    if (resetStepRef.current) {
                      resetStepRef.current();
                    }
                  }, DURATION_PERIOD);
                });
              }
            },
          },
        ]);
      }
      // }
      // }, DURATION_PERIOD);
    };
    return posePeriodInterval.current;
  };

  const getInstructionsFromDb = async () => {
    let dbInstruction = instructionInDb[0]?.instuction;
    // UELogEvent("StencilAnimation. dbInstruction", {
    //   "dbInstruction": JSON.stringify(dbInstruction)
    // })
    if (dbInstruction === undefined || dbInstruction.length <= 0) {
      // UELogEvent("StencilAnimation. no instructions found", {
      //   "dbInstruction": JSON.stringify(dbInstruction)
      // })
      props.navigation.navigate("WithQuote");
      Alert.alert(
        "Try Again!",
        "We are unable to load guiding information for you."
      );
      return;
    }
    instructionArr = dbInstruction;
    console.log("**** getInstructionFromDb: " + instructionArr);

    if (props.toVDO !== undefined && props.toVDO) {
      toImageName("VDO");
    } else if (currentImage === "RCB1") {
      //   /*
      //     By getting RCB data from redux
      //     I'll know which images have been captured
      //     so that if whichever is missing toImageName(imageName) will
      //     show instruction about it.

      //     I'll also be using length of the total extra rcbook/card images
      //     to name the same.
      //   */
      toImageName("RCB1");
    } else if (currentImage === "RCB2") {
      toImageName("RCB2");
    } else if (currentImage === "MORE") {
      setIsMoreRCB(true);
      toImageName("RCB1");
    }

    // nextStencil("init");
  };
  const nextStencil = (instructionType = "next") => {
    moveToNextStencil({ type: instructionType });
  };

  const prevStencil = (instructionType = "prev") => {
    moveToNextStencil({ type: instructionType });
  };

  /* @NEWORDER */
  const toImageName = (imageName) => {
    moveToNextStencil({ type: "toImageName", payload: imageName });
  };

  const imageInstructionTop = (instruction) => {
    return (
      <View style={styles.topInstructionView}>
        <Text style={styles.topInstructionText}>{instruction.stepTitle}</Text>
      </View>
    );
  };

  const instructionWithImage = (instruction) => {
    return (
      <View style={styles.instructionImageView}>
        {imageInstructionTop(instruction)}
        <Image
          key={instruction.displayOrder}
          style={styles.stencilStyle}
          resizeMode="stretch"
          source={{ uri: instruction.stepAssests }}
        />
        {true && (
          <TextInput
            returnKeyType="done"
            keyboardType={"number-pad"}
            style={{ flex: 0.2, marginHorizontal: 5, marginVertical: 5 }}
            label={"Enter Odometer Reading (in Km)"}
            value={"" + odometerReadings}
            onChangeText={(value) => {
              setOdometerReadings(value);
            }}
            errorMsge={""}
          />
        )}
        {imageInstructionBottom(instruction)}
      </View>
    );
  };

  const imageInstructionBottom = (instruction) => {
    return (
      <View style={styles.bottomInstructionView}>
        <Text style={styles.bottmInstructionText}>{instruction.stepTitle}</Text>
        <PrimaryButton
          style={styles.bottomInstructionButton}
          disabled={false}
          onPress={() => {
            getButtonAction(instruction)();
          }}
        >
          {getButtonName(instruction)}
        </PrimaryButton>
      </View>
    );
  };

  const onRetryCallback = (uri, DocumentImageName) => {
    // UELogEvent("StencilAnimation. onRetryCallback. ", {
    //   "URI": JSON.stringify(uri),
    //   "DocumentImageName": JSON.stringify(DocumentImageName)
    // })
    if (
      DocumentImageName === RCB1 ||
      DocumentImageName === RCB2 ||
      DocumentImageName === DBD
    ) {
    } else if (DocumentImageName === VDO) {
    }
  };

  const onProceedCallback = (uri, DocumentImageName) => {
    if (
      DocumentImageName === RCB1 ||
      DocumentImageName === RCB2 ||
      DocumentImageName === DBD ||
      DocumentImageName.includes("RCB")
    ) {
      console.log("**** ProceedCallback if UploadFile: " + DocumentImageName);
      UploadFile(
        uri,
        DocumentImageName,
        ".jpg",
        () => {
          props.navigation.navigate("WithQuote");
        },
        () => {
          addSensorImageData(".jpg", true, DocumentImageName);
        },
        () => {
          addSensorImageData(".jpg", true, DocumentImageName);
        }
      );
      nextStencil("next");
    } else if (DocumentImageName === VDO) {
      // ***** IMPORTANT *******
      // this Logic is written in Camera.js
      // considering VDO is last file else we can check array[array.length-1] is last doc.
      // UELogEvent("StencilAnimation. ProceedCallback if UploadFile",
      //   {
      //     "DocumentImageName": JSON.stringify(DocumentImageName)
      //   })
      console.log(
        "**** ProceedCallback else before UploadFile: " + DocumentImageName
      );
      props.navigation.navigate("VideoPIProgress");
      UploadFile(
        uri,
        DocumentImageName,
        ".jpg",
        () => {
          props.navigation.navigate("WithQuote");
        },
        () => {
          var ext = DocumentImageName == "VDO" ? ".mp4" : ".jpg";
          addSensorImageData(ext, true, DocumentImageName);
        },
        () => {
          var ext = DocumentImageName == "VDO" ? ".mp4" : ".jpg";
          addSensorImageData(ext, false, DocumentImageName);
        }
      );
      console.log(
        "**** ProceedCallback after UploadFile: " + DocumentImageName
      );
      console.log(
        "**** ProceedCallback after navigate Progress: " + DocumentImageName
      );
    }
  };

  const addSensorImageData = (ext, ImageStatus, DocumentImageName) => {
    var attemptCount = PIRetryCount[0]?.retryCount + 1;
    var activityId = PIVechicleData[0]?.activityId;
    var fileName = activityId + "_" + DocumentImageName + ext;
    const PILocation = realm.objects("PILocation");
    const latitude = PILocation[0]?.lat;
    const longitude = PILocation[0]?.long;

    //adding sensor data
    sensorImageDetails.push({
      attemptCount: attemptCount,
      fileName: fileName,
      latitude: latitude,
      longitude: longitude,
      pose: DocumentImageName,
      success: ImageStatus,
      timestamp: new Date().getTime(),
    });
    dispatch({
      type: "SENSOR_DETAILS",
      payload: sensorImageDetails,
    });
  };

  const goToPreviewMedia = (uri, documentImageName) => {
    props.navigation.navigate("PreviewMedia", {
      uri: uri,
      DocumentImageName: documentImageName,
      onRetry: onRetryCallback,
      onProceed: onProceedCallback,
    });
  };

  const getButtonAction = (instruction) => {
    if (instruction.imageName === RCB1 || instruction.imageName === RCB2) {
      const takeSnapshot = async () => {
        const options = {
          quality: 0.2,
          base64: true,
          orientation: "landscapeLeft",
        };
        console.log("*** takeSnapshot before takePictureAsync");
        const data = await props.myCamera.takePictureAsync(options);
        // UELogEvent("StencilAnimation. getButtonAction, data", {
        //   "data": JSON.stringify(data.uri)
        // })
        console.log("*** takeSnapshot after takePictureAsync: " + data.uri);
        setImagePreview(true);
        setImagePreviewUri(data.uri);
        // Alert.alert("Uri", data.uri);
        console.log("*** takeSnapshot before captureRef");
        const captureTimeout = setTimeout(() => {
          clearTimeout(captureTimeout);
          captureRef(viewShotRef, {
            format: "jpg",
            quality: 0.8,
          }).then(
            (uri) => {
              // UELogEvent("StencilAnimation. captureRef, uri", {
              //   "uri": JSON.stringify(uri)
              // })
              console.log("*** takeSnapshot in then captureRef: " + uri);
              setImagePreview(false);
              /* @RCB 
                  changing DocumentImageName when there will be Extra RC Book/Card Images
                  I'll be using length of the array of extra images which will determine
                  each image number.
                  so if array is empty I'll using 3 suffix to RCB
                  because there are already two RCB Images.
                  so DocumentImageName = RCB3 if length is 0

                  isMoreRCB checks if we are capturing extra photos
                  it will true if so.
                */
              let imageName = instruction.imageName;
              if (isMoreRCB) {
                imageName = `RCB${MoreRCBImages.length + 3}`;
              }
              goToPreviewMedia(uri, imageName);
            },
            (error) => {
              // UELogEvent("StencilAnimation. getButtonAction, error", {
              //   "error": JSON.stringify(error)
              // })
              console.log("*** takeSnapshot in error captureRef: " + error);
              // Alert.alert("ViewShot Uri Error", "" + error);
              setImagePreview(false);
            }
          );
        }, 700);
      };
      return takeSnapshot;
    } else if (instruction.imageName === VDO) {
      return stopScreenRecordingCallback;
    } else if (instruction.imageName === DBD) {
      const getODO = async () => {
        if (odometerReadings === undefined || odometerReadings.length <= 0) {
          Alert.alert("Enter valid readings");
          return;
        }
        savaDataToRealm(odometerReadings);
        nextStencil("next");
      };
      return getODO;
    }
    return () => {
      Alert.alert(
        "Oops!",
        "We are unable to take picture for " + instruction?.imageName
      );
    };
  };

  const savaDataToRealm = (value) => {
    console.log("**** saveDataToRealm Odometer: " + value);
    realm.write(() => {
      console.log("**** saveDataToRealm before Odometer: " + value);
      realm.delete(realm.objects("PIOdometerData"));
      realm.create("PIOdometerData", {
        readings: value,
      });
    });
    console.log(
      "**** saveDataToRealm after Odometer: " +
      JSON.stringify(realm.objects("PIOdometerData"))
    );
  };

  const getButtonName = (instruction) => {
    if (instruction.imageName === RCB1 || instruction.imageName === RCB2) {
      return "Capture";
    } else if (instruction.imageName === VDO) {
      return "Stop";
    } else if (instruction.imageName === DBD) {
      return "Submit";
    }
    return "Next";
  };

  const getLatLong = () => {
    const PILocation = realm.objects("PILocation");
    const latitude = PILocation[0]?.lat;
    const longitude = PILocation[0]?.long;
    if (
      locationRetryCount < 2 &&
      (latitude === undefined || longitude === 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;
    } else {
      setCurrentLatitude(latitude);
      setCurrentLongitude(longitude);
    }
  };

  // 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();
    setDateTime(
      date +
      "/" +
      month +
      "/" +
      year +
      " - " +
      hour +
      ":" +
      minute +
      ":" +
      seconds
    );
  };

  const getStopVideoInstruction = (instruction) => {
    const imageName = instruction?.imageName;
    if (imageName === VDO) {
      return (
        <View style={styles.stopVideoInstructionView}>
          <TouchableOpacity
            style={{ justifyContent: "center", alignItems: "center" }}
            onPress={() => {
              if (!disableStopVideoButton) {
                stopScreenRecordingCallback(true);
                /* only able to turn off the torch at the end */
                if (
                  props.toggleTorch !== undefined &&
                  props.flashState !== undefined &&
                  props.flashState
                ) {
                  props.toggleTorch();
                }
              }
            }}
          >
            <Icon
              name="stop-circle-o"
              size={48}
              color={disableStopVideoButton ? Colors.inactiveText : "red"}
              style={{ backgroundColor: "transparent", paddingHorizontal: 5 }}
            />
          </TouchableOpacity>
        </View>
      );
    }
  };

  const getStepVideoInstruction = (instruction) => {
    const imageName = instruction?.imageName;
    if (imageName === VDO) {
      return (
        <Steps
          navigation={props.navigation}
          nextStepCallback={nextStepRef}
          prevStepCallback={prevStepRef}
          resetCallback={resetStepRef}
          instructionArr={instructionArr}
        />
      );
    }
  };

  const instruction = (instruction) => {
    const title = instruction?.TSurveyInstructions[0]?.instructionData;
    const imageName = instruction?.imageName;
    if (imageName !== VDO) {
      return (
        <View style={styles.instructionViewMain}>
          <View style={styles.dateTimeView}>
            <Text style={styles.instructionDateTimeText}>
              {"Lat:" +
                " " +
                currentLatitude +
                "  " +
                "Lon:" +
                "  " +
                currentLongitude +
                "  " +
                "    |    " +
                "Digit App" +
                "    |    " +
                dateTime}
            </Text>
          </View>
          <View style={styles.instructionView}>
            <Text style={styles.instructionText}>
              {isMoreRCB
                ? "Take a picture of the other pages of the RC book/card"
                : title}
            </Text>
            <PrimaryButton
              style={styles.instructionButton}
              disabled={false}
              onPress={() => {
                getButtonAction(instruction)();
              }}
            >
              {getButtonName(instruction)}
            </PrimaryButton>
          </View>
        </View>
      );
    }
  };

  const isInstructionWithImage = (instruction) => {
    if (instruction == undefined) {
      return false;
    }
    if (instruction.type === "input" || instruction.imageName === DBD) {
      return true;
    } else if (
      instruction.type === "image" &&
      (instruction.imageName === RCB1 || instruction.imageName === RCB2)
    ) {
      return false;
    } else {
      return false;
    }
  };

  const startVideo = () => {
    console.log(
      "**************************** startVideo ************************************************"
    );
    // if (props.startScreenRecording) {
    //   setDisableStopVideoButton(true);
    //   // posePeriodIntervalFun();
    //   console.log("*** 0 startAnim before start");
    //   const res = await props.startScreenRecording();

    //   /* I have assigned a different variable
    //   to check for undefined, stringfying res may cause a problem
    //   */
    //   let UEdata = res;
    //   if (UEdata === undefined) {
    //     UELogEvent("StencilAnimtion, startVideo,", {
    //       "res": "undefined"
    //     })
    //   }

    // console.log("*** 1 startAnim after start " + JSON.stringify(res));
    const res = startCameraRecording();
    console.log("StencilAnimation,AnimatedRef. ", animatedRef.current);
    if (res && animatedRef.current !== undefined) {
      const holdOn = setTimeout(() => {
        clearTimeout(holdOn);
        posePeriodIntervalFun();
        animatedRef.current[0].start(() => {
          console.log("*** startAnim animation finished");
        });
        console.log("**** 2 startVideo Animation started");
        const [pauseTimer, resumeTimer] = Timer(() => {
          pauseTimerRef.current();
          console.log("*** 4 startAnim animation timeout finished");
          stopScreenRecordingCallback(false);
        }, ANIM_DURATION);
        resumeTimerRef.current = resumeTimer;
        pauseTimerRef.current = pauseTimer;
      }, HOLD_ON_TIME);
    } else {
      // UELogEvent("StencilAnimation, startVideo, recording got cancelled")
      setStartRecording(true);
      Alert.alert("Recording Cancelled!");
    }
  };

  /* camera recording  */

  const startCameraRecording = async () => {
    // default to mp4 for android as codec is not set

    // Below promise returns a json object consisting of supported FPS
    // Only those fps can be used.
    // const FPSRange = await props.myCamera.getSupportedPreviewFpsRange();
    // console.log("StencilAnimation. FPSRange.", FPSRange);

    const options = {
      // /* values taken from react-native-record-screen+0.4.0.patch file
      // Log.i("*****", "video bitrate: " + 1024000 + " frames: " + 16 + " resolution: 480 x 640")
      // height:480,width:640
      orientation: "landscapeLeft",
      base64: true,
      // maxDuration: ANIM_DURATION + EXTRA_TIME + HOLD_ON_TIME,
      quality: "720p",
      videoBitrate: 2048000,
      fps: 15,
      // mute:true
    };
    // Shifting start Recording here
    const res = props.myCamera
      .recordAsync(options)
      .then(({ uri, codec = "mp4" }) => {
        console.log("URI", uri);
        const imageName = "VDO";
        props.navigation.navigate("PreviewMedia", {
          uri: uri,
          DocumentImageName: imageName,
          onRetry: (uri, imageName) => { },
          onProceed: (uri, imageName) => {
            /* 
            disabling the start button so that re-render does not happen.
            */
            setStartRecording(false);
            const myTimeout = setTimeout(() => {
              clearTimeout(myTimeout);
              Orientation.lockToPortrait();
              props.navigation.navigate("Odometer");
              UploadFile(
                uri,
                imageName,
                ".mp4",
                () => {
                  props.navigation.navigate("WithQuote");
                },
                () => {
                  addSensorImageData(".mp4", true, imageName);
                },
                () => {
                  addSensorImageData(".mp4", false, imageName);
                }
              );
              // setStartRecording(true);
            }, 1000);
          },
        });
      })
      .catch((error) => {
        console.log(
          "StencilAnimation. camera options ---->",
          JSON.stringify(error)
        );
        setStartRecording(true);
        Alert.alert(error?.message);
      });

    if (res) {
      console.log(
        "StencilAnimtion startCameraRecording, camera recording started."
      );
      return true;
    } else {
      return false;
    }
  };

  const stopCameraRecording = () => {
    console.log("StencilAnimation stopCameraRecording.");
    props.myCamera.stopRecording();
  };

  const StartRecordingMainView = () => {
    return (
      <View style={styles.startRecordingView}>
        <View style={styles.startRecordingSubView}>
          <Text style={styles.textTitle}>Please be near chassis number</Text>
          <View style={styles.lineView} />
          <PrimaryButton
            style={styles.startRecordingButton}
            onPress={() => {
              /* I have moved setEaseLinear(true) to dismiss of the instructionModal */
              setStartRecording(false);
              startVideo();
            }}
          >
            {"Start Recording"}
          </PrimaryButton>
          <Text style={styles.textSubTitle}>
            Please note: once begin recording, you'll have to complete the
            entire inspection
          </Text>

          {/* adding flash support */}
          <View
            style={{
              flexDirection: "row",
              alignItems: "center",
              alignSelf: "center",
            }}
          >
            <Text style={[style.muliBoldDB, { color: Colors.white }]}>
              Flash{" "}
              {props.flashState !== undefined && props.flashState
                ? "On"
                : "Off"}
            </Text>
            <TouchableOpacity
              style={styles.flashIconButtonSurface}
              onPress={() => {
                console.log("^^^^^ STARTED TORCH ^^^^^^");
                if (props.toggleTorch) {
                  props.toggleTorch();
                  console.log("^^ TORCH STATE ^^^", props.flashState);
                }
              }}
            >
              <MIcon
                name={
                  props.flashState !== undefined && props.flashState
                    ? "flash-on"
                    : "flash-off"
                }
                size={24}
                color={Colors.white}
                style={{ backgroundColor: "transparent", paddingHorizontal: 5 }}
              />
            </TouchableOpacity>
          </View>
        </View>
      </View>
    );
  };

  useEffect(() => {
    // if (instructionManager.imageName === RCB1) {
    //   setEnableRCBPreview(true);
    // } else {
    //   setEnableRCBPreview(false);
    // }
    if (instructionManager.imageName === VDO) {
      setStartRecording(true);
      setInstructionsModalVisible(true);
      setDisableStopVideoButton(true);
      // setInstructionsModalVisible(false);
    } else {
      setStartRecording(false);
      setEaseAnimation(false);
      setInstructionsModalVisible(false);
    }
  }, [instructionManager.imageName]);

  const stopIt = async () => {
    // if(animatedRef.current){
    //   clearTimeout(animatedRef.current)
    // }
    if (extraTimeRef.current) {
      clearTimeout(extraTimeRef.current);
    }
    if (posePeriodInterval.current) {
      clearInterval(posePeriodInterval.current);
    }
    if (resetStepRef.current) {
      resetStepRef.current();
    }
    if (props.stopScreenRecording) {
      console.log("*** 6 startAnim animation finished");
      // await props.stopScreenRecording();
      stopCameraRecording();
      setStartRecording(true);
    }
    /* only able to turn off the torch at the end */
    console.log("^^^^^ TORCH STATE ^^^^", props.flashState);
    if (
      props.toggleTorch !== undefined &&
      props.flashState !== undefined &&
      props.flashState
    ) {
      console.log("^^^ TORCH OFF ^^^^");
      props.toggleTorch();
    }
    setDisableStopVideoButton(true);
  };

  const stopScreenRecordingCallback = (userStopped = true) => {
    if (userStopped) {
      // UELogEvent("StencilAnimation. stopScreenRecordingCallback, user stopped the recording.");
      console.log("*** 5 stopAnim  user finished");
      stopIt();
    } else {
      // UELogEvent("StencilAnimation. stopScreenRecordingCallback, auto stopped the recording.");

      setDisableStopVideoButton(false);
      extraTimeRef.current = setTimeout(() => {
        // allow extra time once ANIM_DURATION finish
        console.log("*** or 5 stopAnim extra timeout finished");
        stopIt();
      }, EXTRA_TIME);
    }
  };

  const InstructionsScreenModal = () => {
    return (
      <View>
        <Modal
          // isVisible={instructionsModalVisible}
          isVisible={true}
          headerImageVisible={false}
          shouldHeaderVisible={false}
        >
          <InstructionsScreen
            startRecording={() => {
              /* Stencil Animation re-render if this easeAnimation set true,
              it would set all the state params to their default values hence the 
              camera recording was not starting.
              I am rendering the AnimationEaseLinear component on dismiss of this modal
              so that the values of states should not reset
              */
              setEaseAnimation(true); // Logic to just change the status,
              setInstructionsModalVisible(false);
            }}
          />
        </Modal>
      </View>
    );
  };

  var Timer = (callback, delay) => {
    var timerId,
      start,
      remaining = delay;

    const pauseTimer = () => {
      clearTimeout(timerId);
      timerId = null;
      remaining -= Date.now() - start;
      return remaining;
    };

    const resumeTimer = () => {
      if (timerId) {
        return;
      }
      start = Date.now();
      timerId = setTimeout(callback, remaining);
    };
    resumeTimer();
    return [pauseTimer, resumeTimer];
  };

  const getFlashButton = (instruction) => {
    const imageName = instruction?.imageName;
    if (imageName === RCB1 || imageName === RCB2) {
      return (
        <View style={styles.flashView}>
          <TouchableOpacity
            style={styles.flashIconButtonSurface}
            onPress={() => {
              console.log("^^^^^ STARTED TORCH ^^^^^^");
              if (props.toggleTorch !== undefined) {
                props.toggleTorch();
              }
            }}
          >
            <MIcon
              name={!props.flashState ? "flash-on" : "flash-off"}
              size={36}
              color={Colors.white}
              style={{ backgroundColor: "transparent", paddingHorizontal: 5 }}
            />
          </TouchableOpacity>
        </View>
      );
    }
  };

  return (
    <ViewShot style={styles.mainView} ref={viewShotRef}>
      <View style={styles.mainView}>
        {easeAnimation && (
          <AnimationEaseLinear
            animationListener={animationListener}
            onAnimationFinish={() => { }}
            ref={animatedRef}
          />
        )}
        {/* {isInstructionWithImage(instructionManager) &&
          instructionWithImage(instructionManager)} */}
        {!isInstructionWithImage(instructionManager) &&
          instruction(instructionManager)}
        {/* {!isInstructionWithImage(instructionManager) &&
          enableRCBPreview &&
          goToRCBPreview(instructionManager)} */}
        {imagePreview && (
          <Image
            key={instructionManager.displayOrder}
            style={styles.previewImageView}
            resizeMode="cover"
            source={{ uri: imagePreviewUri }}
          />
        )}
        {startRecording && StartRecordingMainView()}
        {getStopVideoInstruction(instructionManager)}
        {getFlashButton(instructionManager)}
        {getStepVideoInstruction(instructionManager)}
      </View>
      {instructionsModalVisible && InstructionsScreenModal()}
    </ViewShot>
  );
});

const styles = StyleSheet.create({
  mainView: {
    flex: 1,
    height: "100%",
    zIndex: zIndex_main_view,
    width: "100%",
    position: "absolute",
    backgroundColor: "transparent",
    justifyContent: "flex-end",
  },
  previewImageView: {
    position: "absolute",
    zIndex: zIndex_snapshot_preview_image,
    width: "100%",
    alignSelf: "center",
    height: "100%",
    backgroundColor: "transparent",
  },
  instructionImageView: {
    flex: 1,
    zIndex: zIndex_image_instruction,
    marginHorizontal: "20%",
    flexDirection: "column",
    justifyContent: "center",
    backgroundColor: "white",
  },
  stencilStyle: {
    flex: 0.6,
    width: "100%",
    alignSelf: "center",
    height: "100%",
    backgroundColor: "transparent",
  },
  instructionViewMain: {
    height: "25%",
    width: "100%",
    zIndex: zIndex_bottom_instruction,
    flexDirection: "column",
    justifyContent: "center",
    backgroundColor: "transparent",
  },
  dateTimeView: {
    flex: 0.4,
    height: "100%",
    width: "100%",
    flexDirection: "row",
    justifyContent: "flex-start",
    backgroundColor: "transparent",
  },
  instructionView: {
    flex: 0.8,
    height: "100%",
    width: "100%",
    flexDirection: "row",
    justifyContent: "flex-start",
    backgroundColor: "rgba(0,0,0,0.3)",
  },
  stopVideoInstructionView: {
    position: "absolute",
    // height: "100%",
    top: 0,
    bottom: 0,
    right: 0,
    zIndex: zIndex_stop_recording,
    // width: "100%",
    flexDirection: "row",
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: "transparent",
  },
  flashView: {
    position: "absolute",
    justifyContent: "center",
    alignItems: "center",
    top: 0,
    bottom: 0,
    right: 0,
    zIndex: zIndex_flash_torch,
  },
  flashViewVDO: {
    position: "absolute",
    justifyContent: "center",
    alignItems: "center",
    top: "18%",
    right: 0,
    zIndex: zIndex_flash_torchVDO,
  },
  flashIconButtonSurface: {
    justifyContent: "center",
    alignItems: "center",
    height: 48,
    width: 48,
  },
  instructionText: {
    flex: 0.8,
    color: "white",
    alignSelf: "center",
    marginLeft: 10,
    fontFamily: "Muli-Bold",
    fontSize: 18,
  },
  instructionDateTimeText: {
    color: "white",
    marginLeft: 10,
    fontFamily: "Muli-Regular",
    fontSize: 18,
  },
  instructionButton: {
    flex: 0.2,
    height: "10%",
    marginRight: 10,
    alignSelf: "center",
  },
  bottomInstructionView: {
    flex: 0.2,
    height: "15%",
    width: "100%",
    flexDirection: "row",
    justifyContent: "center",
    backgroundColor: "white",
  },
  bottmInstructionText: {
    flex: 0.7,
    color: "black",
    alignSelf: "center",
    marginLeft: 10,
    fontFamily: "Muli-Bold",
  },
  bottomInstructionButton: {
    flex: 0.3,
    height: "10%",
    marginRight: 10,
    alignSelf: "center",
  },
  topInstructionView: {
    flex: 0.2,
    width: "100%",
    height: "100%",
    justifyContent: "center",
    backgroundColor: "white",
  },
  topInstructionText: {
    color: "black",
    alignSelf: "flex-start",
    marginLeft: 10,
    fontFamily: "Muli-Bold",
  },
  startRecordingView: {
    position: "absolute",
    zIndex: zIndex_start_recording,
    width: "100%",
    height: "100%",
    justifyContent: "center",
    backgroundColor: "transparent",
  },
  startRecordingSubView: {
    width: "60%",
    height: "60%",
    alignSelf: "center",
    borderRadius: 10,
    justifyContent: "center",
    backgroundColor: "rgba(0, 0, 0, 0.8)",
  },
  textTitle: {
    color: "white",
    fontSize: 12,
    fontFamily: "Muli-Bold",
    paddingHorizontal: 10,
    alignSelf: "center",
  },
  textSubTitle: {
    color: Colors.inactiveText,
    fontSize: 10,
    fontFamily: "Muli-Regular",
    alignSelf: "center",
    paddingHorizontal: 10,
    marginVertical: 5,
  },
  lineView: {
    width: "80%",
    height: 0.5,
    marginVertical: 10,
    backgroundColor: Colors.inactiveText,
    alignSelf: "center",
  },
  startRecordingButton: {
    width: "50%",
    height: "10%",
    alignSelf: "center",
  },
});

export default {
  StencilAnimation,
  ANIM_DURATION,
  DURATION_PERIOD,
  NO_OF_POSES,
  OBJ_WIDTH,
  ANIMATION_TRACK,
};
