import React, { useEffect, useRef, useState } from "react";
import {
  StyleSheet,
  View,
  Image,
  Text,
  BackHandler,
  ScrollView,
  Alert,
  StatusBar,
  Platform,
  Dimensions,
  PermissionsAndroid,
  Linking,
} from "react-native";
import {
  ANDROID_REQUEST,
  canGoVideoPi,
  WEB_REQUEST,
  is2Wflow,
  shouldWatchDemoVideo,
} from "react-native-digitcamera/src/common/Constants";

import { translate } from "react-native-digitcamera/src/common/localize/i18n";
import Orientation from "../../../react-native-orientation";
import Geolocation from "@react-native-community/geolocation";
import { getTimeZone } from "react-native-localize";
import { TouchableOpacity } from "react-native-gesture-handler";
import RNFetchBlob from "rn-fetch-blob";
import { SELFSURVEYSERVICE_DOCUMENT_URL } from "react-native-digitcamera/src/Api/ApiUrls";
import ViewShot, { captureRef } from "react-native-view-shot";
import Carousel, { Pagination } from "react-native-snap-carousel";
import Header from "../Screens/Header";
import { PrimaryButton, Spinner } from "../common/ThemedComponents";
import Database from "../../../../Components/common/DAsyncStorage";
import { useIsFocused } from "@react-navigation/native";
import { useIsAppForeground } from "../common/useIsForeground";

import { measureConnectionSpeed } from "react-native-network-bandwith-speed";
import { instructionData } from "react-native-digitcamera/src/common/Services/instruction";
import {
  CV,
  TWO_WHELLER,
  PRIVATE_CAR,
  PRIVATE_CAR_PAYD,
} from "react-native-digitcamera/src/Screens/OfflineFlow/LocalData";
import { dispatch } from "react-native-digitcamera/src/common/RootNavigation";
import { useDispatch, useSelector } from "react-redux";
import NetInfo from "@react-native-community/netinfo";

import {
  firebaseAttributes,
  errorRecord,
  firebaseEvents,
} from "../common/libEventLog/libCrashlytics/libCrashlyticsEvent";

import {
  startCapturingSensorData,
  cleanSensorDataArr,
  unsubscribeSensors,
} from "../common/SensorData";
import UserExperior from "react-native-userexperior/UserExperior";

const not_blur = require("../common/Image/not_blur.png");
const open_area_good_light = require("../common/Image/open_area_good_light.png");
const maintain_distance = require("../common/Image/maintain_distance.png");
const rc_book = require("../common/Image/rc_book.png");
const instruction = require("../common/Image/instruction.png");
const horizontalModePhone =
  "https://d2h44aw7l5xdvz.cloudfront.net/CRM/PRM/horizontal_mode_phone.png";
const vehicle10ft =
  "https://d2h44aw7l5xdvz.cloudfront.net/CRM/PRM/10ft_distance_gif.gif";
const iOS = Platform.OS === "ios";

var isFocused;

import {
  UELogEvent,
  UELogMessage,
} from "../common/libEventLog/UserExperior/LibUserExperior";
import Colors from "react-native-digitcamera/src/common/Colors";
import { traceUserMobile } from "../../../../Components/common/Trace";
import style from "../../../../Components/common/CommonStyle";
import { checkInternetSpeed } from "react-native-digitcamera/src/Screens/OfflineFlow/CommonFunc";
let instuction = [];
var activityId,
  activityTypeId,
  licensePlateNumber,
  toWithQuote,
  toTutorial,
  quoteNumber;

const RCB_POINTS = [
  {
    image: rc_book,
    heading:
      "Keep your vehicle’s Registration Certificate (RC Book/Card) ready",
    subHeading: [],
  },
];

const NON_VIDEOPI_POINTS = [
  {
    image: open_area_good_light,
    heading: "Before recording the video please make sure :",
    subHeading: [
      { points: "Your vehicle is in an open space with good light" },
      { points: "Your vechicle is clean" },
      // { points: "Your device camera lens is clean" },
    ],
  },
  // {
  //   image: maintain_distance,
  //   heading: "While clicking the images, please make sure:",
  //   subHeading: [
  //     { points: "You maintain 4-5 feet distance from your vehicle" },
  //     { points: "Edges of the vehicle are also captured in the images" },
  //     { points: "Captured images are not blurred" },
  //   ],
  // },
  {
    image: rc_book,
    heading:
      "Keep your vehicle’s Registration Certificate (RC Book/Card) handy",
    subHeading: [],
  },
  {
    image: instruction,
    heading:
      "To help you click the correct image, simply refer to the image and instructions given at each step and you will be done in no time!",
    subHeading: [],
  },
];

const Toturial = ({ navigation, route }) => {
  /*
  using React.createRef() instead of useRef.
  Potential Bug fix for 
  Invariant Violation: Argument appears to not be a ReactComponent, keys: current  
  https://stackoverflow.com/questions/54939413/invariant-violation-argument-appears-to-not-be-a-reactcomponent
  */
  const nextcarousel = React.createRef();
  const [currentIndex, SetCurrentIndex] = useState(0);
  const [toturialData, setToturialData] = useState([]);
  const [isLoading, SetIsLoading] = useState(true);
  const [isRCBRequired, setIsRCBRequired] = useState(false);
  const [, updateState] = React.useState();

  const forceUpdate = React.useCallback(() => updateState({}), []);

  // var DataSpeed;
  const network = useSelector((state) => state.network);
  const { isInternetReachable } = network;
  var isInternetConnected;
  useEffect(() => {
    if (isInternetReachable === true) {
      isInternetConnected = true;
    } else if (isInternetReachable === false) {
      isInternetConnected = false;
    }
  }, [network]);

  const updateDbAndRedux = async () => {
    dispatch({
      type: "CLEAR_RCB_DATA",
    });

    await Database.update("PIDeeplink", {
      isFromLink: false,
    });
  };
  const { isPAYD } = route.params;
  console.log("[Info] . Toturial . isPAYD ", isPAYD);
  const dispatch = useDispatch();
  isFocused = useIsFocused();
  const isForeground = useIsAppForeground();

  /* Get max dimension for screen width */
  const getMaxWidth = () => {
    return Math.round(
      Math.min(Dimensions.get("screen").height, Dimensions.get("screen").width)
    );
  };

  /*Initial SCREEN_WIDTH*/
  let SCREEN_WIDTH = getMaxWidth();

  const loadInstructions = async () => {
    var RealmData = await Database.get("PIVechicleData");
    activityId = RealmData?.activityId;
    activityTypeId = RealmData?.activityTypeId;
    licensePlateNumber = RealmData?.licensePlateNumber;
    toWithQuote = RealmData?.toWithQuote;
    toTutorial = RealmData?.toTutorial;
    quoteNumber = RealmData?.quoteNumber;
    console.log(
      "*** Toturial useEffect",
      activityId,
      activityTypeId,
      licensePlateNumber,
      toWithQuote,
      toTutorial,
      quoteNumber,
      isInternetConnected
    );
    if (!!isInternetConnected === true) {
      if (activityId != 0) {
        getInstruction();
      }
    } else if (!!isInternetConnected === false) {
      await getLocalInstruction();
      UELogEvent("Offline Flow : tutorial.js", {
        mode: "offline",
      });
    }
  };

  useEffect(() => {
    //disable auto withQuote navigation
    updateDbAndRedux();
    loadInstructions();
    startCapturingSensorData();
    if (isForeground) {
      Orientation.lockToPortrait();
    }

    traceUserMobile();

    if (!iOS) {
      const Immersive = require("react-native-immersive").Immersive;
      Immersive.setImmersive(false);
      StatusBar.setTranslucent(false);
    }
    Orientation.lockToPortrait();
    /* Incase if there is orientation change */
    SCREEN_WIDTH = getMaxWidth();

    // setTutorialData(activityTypeId);
    let unsubscribe = navigation.addListener("focus", () => {
      Orientation.lockToPortrait();
      /* Incase if there is orientation change */
      SCREEN_WIDTH = getMaxWidth();
      if (!iOS) {
        const Immersive = require("react-native-immersive").Immersive;
        Immersive.setImmersive(false);
      }
    });

    saveToRealm();

    // dynatrace
    traceUserMobile();

    return () => {
      unsubscribe();
      cleanSensorDataArr();
      unsubscribeSensors();
    };
  }, []);

  /* setQuickTips */
  const setQuickTips = (hasRCB) => {
    /* 
      if instructions has rcb, render rcb tips
      if instructions doesnt have rcb, then render video tips
    */

    if (canGoVideoPi(activityTypeId)) {
      if (hasRCB) {
        setToturialData(RCB_POINTS);
      }
    } else {
      setToturialData(NON_VIDEOPI_POINTS);
    }
  };

  const saveToRealm = async () => {
    try {
      await Database.update("PIRCBCount", {
        addMoreCount: 2,
      });

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

      await Database.update("PIUploadedCount", {
        uploadedCount: 0,
      });
    } catch (error) {
      console.log("Error", error);
    }
  };

  // check type of request
  const instructionWebOrAndroid = (activityTypeId) => {
    activityTypeId = 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
  const 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;
  };

  const subscribeSensorData = () => {};

  const getLocalInstruction = async () => {
    instuction = [];
    var RealmData = await Database.get("PIVechicleData");
    var activityTypeId = RealmData?.activityTypeId;
    let V_instuction = await InstuctionByType(activityTypeId);
    console.log(
      "**** instruction: before getLocalInstruction",
      V_instuction?.TSurveySteps
    );
    V_instuction?.TSurveySteps.map((item) => {
      if (
        is2Wflow(activityTypeId) &&
        V_instuction?.stencilAssets !== undefined
      ) {
        /*adding stencil assets to instructions*/
        const stencilItem = V_instuction?.stencilAssets.find(
          (asset) => asset.poseName === item.imageName
        );
        console.log("^^^^^^^^ STENCIL ITEM OBJ........", stencilItem);
        if (stencilItem !== undefined) {
          const stencilAssetURI = stencilItem.stencilAssetLink;
          item["stepStencilAssests"] = stencilAssetURI;
        }
      }
      console.log("000000000000", item);
      instuction.push(item);
      console.log(
        "**** instruction: added",
        JSON.stringify(instruction, null, "  ")
      );
    });

    // sorting instructions
    instuction.sort((obj1, obj2) => {
      let id1 = obj1.displayOrder;
      let id2 = obj2.displayOrder;
      return id1 - id2;
    });

    await Database.update("PIVechicleInstruction", {
      instuction: JSON.stringify(instuction),
    });
    setTimeout(() => {
      SetIsLoading(false);
    }, 1000);

    // setQuickTips
    const rcbObj = instuction.find((element) => {
      return element.imageName.includes("RCB");
    });

    const demoVideoUriObj = instuction.find((element) => {
      return element.imageName === "VDO";
    });

    const demoVideoUri = demoVideoUriObj?.stepAssests;
    console.log("($) Toturial . demoVideoUri: ", demoVideoUri);
    await Database.set("PIDemoVideoURI", { uri: demoVideoUri });

    let item = instuction.find((item) => item.imageName === "VDO");

    if (item) {
      if (item?.TSurveyInstructions?.length !== 0) {
        const imageTypeInstructions = item?.TSurveyInstructions.filter(
          (item) => item?.instructionTitle === "Quick Tips"
        );

        await Database.set("PIQuickTips", imageTypeInstructions);
      }
    }

    if (canGoVideoPi(activityTypeId)) {
      // Video PI quick tips
      // for PAYD flow there will be no rcb required
      Orientation.lockToLandscapeLeft();
      if (isPAYD) {
        moveToDemoVideo(demoVideoUri);
        // } else {
        //   moveToQuickTips();
        // }
      } else {
        if (rcbObj) {
          moveToRCBQuickTips();
        } else {
          moveToQuickTips();
        }
      }
      // moveToQuickTips();
    } else {
      // 2w & cv quick tips
      setQuickTips(false);
    }
  };

  const InstuctionByType = async (activityTypeId) => {
    var PILocalInstruction = await Database.get("PILocalInstruction");
    let localInstruction = [];
    switch (activityTypeId) {
      case 63:
        localInstruction = PILocalInstruction.PRIVATE_CAR_PAYD;
        break;
      case 5:
        localInstruction = PILocalInstruction.PRIVATE_CAR;
        break;
      case 26:
        localInstruction = PILocalInstruction.TWO_WHELLER;
        break;
      case 30:
        localInstruction = PILocalInstruction.CV;
        break;
      default:
        localInstruction = PRIVATE_CAR;
        break;
    }
    return localInstruction;
  };

  // get vechicle instructions
  const getInstruction = async () => {
    try {
      UELogEvent("getInstruction Started..", {
        "Activity Type Id": activityTypeId,
      });
      let requestTypeName = instructionWebOrAndroid(activityTypeId);
      UELogMessage("Response from instructionWebOrAndroid", {
        "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,
        activityId: activityId,
      });
      UELogMessage("Response from instruction data", {
        "Vehicle Instructions": JSON.stringify(V_instuction),
      });

      // DataSpeed = await measureConnectionSpeed();
      // if (false) {
      instuction = [];
      console.log("**** instruction: before");
      V_instuction?.TSurveySteps.map((item) => {
        if (
          is2Wflow(activityTypeId) &&
          V_instuction?.stencilAssets !== undefined
        ) {
          /*adding stencil assets to instructions*/
          const stencilItem = V_instuction?.stencilAssets.find(
            (asset) => asset.poseName === item.imageName
          );
          // UELogEvent("Toturial, fetching stencil data for 2w from V_instructions", {
          //   "stencilItem": JSON.stringify(stencilItem)
          // })
          console.log("^^^^^^^^ STENCIL ITEM OBJ........", stencilItem);
          if (stencilItem !== undefined) {
            const stencilAssetURI = stencilItem.stencilAssetLink;
            item["stepStencilAssests"] = stencilAssetURI;
          }
        }

        instuction.push(item);
        console.log("**** instruction: added", item);
      });

      // sorting instructions
      instuction.sort((obj1, obj2) => {
        let id1 = obj1.displayOrder;
        let id2 = obj2.displayOrder;
        return id1 - id2;
      });

      // New requirement -> Video shoot should be bring to first
      // if (instuction.length > 0) {
      //   let vdoObj = instuction[instuction.length - 1];
      //   instuction.splice(0, 0, vdoObj);
      //   instuction.pop();
      // }

      await Database.update("PIVechicleInstruction", {
        instuction: JSON.stringify(instuction),
      });
      var RealmInstructionData = await Database.get("PIVechicleInstruction");
      console.log(
        "*** Toturial RealmInstructionData length ",
        JSON.parse(RealmInstructionData.instuction).length
      );
      setTimeout(() => {
        SetIsLoading(false);
      }, 1000);
      UELogMessage("Instrutions Details", {
        "Request Type Value": JSON.stringify(requestTypeValue),
        "Activity Id": JSON.stringify(activityId),
        "Activity Type Id": JSON.stringify(activityTypeId),
      });
      firebaseEvents(
        "Instruction",
        { requestTypeValue: requestTypeValue },
        activityId,
        activityTypeId,
        ""
      );

      // setQuickTips
      const rcbObj = instuction.find((element) => {
        return element.imageName.includes("RCB");
      });

      const demoVideoUriObj = instuction.find((element) => {
        return element.imageName === "VDO";
      });

      const demoVideoUri = demoVideoUriObj?.stepAssests;
      console.log("($) Toturial . demoVideoUri: ", demoVideoUri);
      await Database.set("PIDemoVideoURI", { uri: demoVideoUri });

      let item = instuction.find((item) => item.imageName === "VDO");

      if (item) {
        if (item?.TSurveyInstructions?.length !== 0) {
          const imageTypeInstructions = item?.TSurveyInstructions.filter(
            (item) => item?.instructionTitle === "Quick Tips"
          );
          await Database.set("PIQuickTips", imageTypeInstructions);
        }
      }

      // Navigate to DemoVideo only for VideoPI
      if (canGoVideoPi(activityTypeId)) {
        // Need Landscape orientation before going for demo video
        Orientation.lockToLandscapeLeft();
        if (rcbObj) {
          moveToRCBQuickTips();
        } else {
          moveToDemoVideo(demoVideoUri);
        }
      } else {
        setQuickTips(false);
      }
    } catch (error) {
      UELogEvent("getInstructions stopped in catch", {
        Error: JSON.stringify(error),
      });
      firebaseAttributes(error);
      errorRecord(error);
      console.log("Error in Tutorial >>> ", error);
      Alert.alert(
        "Oops! Unable to proceed",
        "We are experiencing technical issue, Please try after sometime. Or Still You can continue with registration number"
      );
      setTimeout(() => {
        SetIsLoading(false);
      }, 1000);
    }
  };

  const moveToRCBQuickTips = async () => {
    // const quickTipsData = [];
    // let item = instuction.find((item) => item.imageName === "VDO");
    // if (item) {
    //   if (item?.TSurveyInstructions?.length !== 0) {
    //     const imageTypeInstructions = item?.TSurveyInstructions.filter(
    //       (item) => item?.instructionTitle === "Quick Tips"
    //     );
    //     const rcbQuickTip = imageTypeInstructions.find(
    //       (item) => item?.quickTipType === "RCB"
    //     );

    //     console.log("[INFO] [TUTORIAL] rcbQuickTip - ", rcbQuickTip);

    //     if (rcbQuickTip) {
    //       quickTipsData.push(rcbQuickTip);

    //     }
    //   }
    // }

    const quickTipsData = await Database.get("PIQuickTips");
    const rcbQuickTips = quickTipsData.find(
      (item) => item?.quickTipType === "RCB"
    );
    navigation.navigate("RCBQuickTips", {
      data: rcbQuickTips ? [rcbQuickTips] : [],
    });
  };

  const moveToQuickTips = () => {
    navigation.navigate("QuickTips");
  };

  const moveToDemoVideo = (videoUri) => {
    navigation.navigate("DemoVideo", { videoUri });
  };

  /* @MOVETORCB */
  // const moveToRCBPreview = () => {
  //   const rcbObj = instuction.find((element) => {
  //     return element.imageName.includes("RCB");
  //   });

  //   if (rcbObj) {
  //     console.log("^^^^^^^ moveToRCBPreview, rcbObj ^^^^^^^", rcbObj);

  //     navigation.navigate("RCBPreviewScreen", {
  //       ProceedCallback: () => {
  //         moveToCamera(false);
  //       },
  //     });
  //   }
  // };

  // const moveToRCBPreviewScreen = () => {
  //   navigation.navigate("RCBPreviewScreen", {
  //     ProceedCallback: () => {
  //       moveNow(false);
  //     },
  //   });
  // };

  const getAndroidPermission = async (toVDO) => {
    console.log("*** Toturial getAndroidPermission before");
    const result = await PermissionsAndroid.requestMultiple([
      PermissionsAndroid.PERMISSIONS.CAMERA,
      PermissionsAndroid.PERMISSIONS.RECORD_AUDIO,
      PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
      PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE,
      PermissionsAndroid.PERMISSIONS.READ_PHONE_STATE,
    ]);
    console.log("*** Toturial getAndroidPermission after await ", result);
    if (
      result["android.permission.CAMERA"] === "granted" &&
      result["android.permission.RECORD_AUDIO"] === "granted" &&
      result["android.permission.WRITE_EXTERNAL_STORAGE"] === "granted" &&
      result["android.permission.READ_EXTERNAL_STORAGE"] === "granted" &&
      result["android.permission.READ_PHONE_STATE"] === "granted"
    ) {
      console.log("*** Toturial getAndroidPermission granted all");
      moveNow(toVDO);
      UELogEvent("Toturial.js, Permissions. ", {
        "External Storage Write": JSON.stringify("granted"),
        "External Storage Read": JSON.stringify("granted"),
        "Phone State": JSON.stringify("granted"),
        Camera: JSON.stringify("granted"),
        Audio: JSON.stringify("granted"),
      });
    } else if (
      result["android.permission.CAMERA"] === "never_ask_again" ||
      result["android.permission.RECORD_AUDIO"] === "never_ask_again" ||
      result["android.permission.WRITE_EXTERNAL_STORAGE"] ===
        "never_ask_again" ||
      result["android.permission.READ_EXTERNAL_STORAGE"] ===
        "never_ask_again" ||
      result["android.permission.READ_PHONE_STATE"] === "never_ask_again"
    ) {
      console.log("*** Toturial getAndroidPermission denied any one");
      Alert.alert(
        translate("Permission denied"),
        "We will be not able to proceed your vehicle inspection"
      );
      await Linking.openSettings();
    }
  };

  const moveToCamera = async (toVDO) => {
    if (Platform.OS === "android") {
      await getAndroidPermission(toVDO);
    } else {
      moveNow(toVDO);
    }
  };

  const moveNow = (toVDO) => {
    navigation.navigate("Camera", {
      activityId,
      activityTypeId,
      licensePlateNumber,
      toVDO: toVDO /* @NEWORDER */,
      instruction: JSON.stringify(instuction),
    });
  };

  const _renderToturial = ({ item, index }) => {
    return (
      <View style={{ margin: 24, flex: 1 }}>
        <ScrollView>
          {item?.boldSubtitle && (
            <View
              style={{
                flexDirection: "row",
                marginVertical: 16,
                alignSelf: "center",
              }}
            >
              <View style={styles.yellowLine} />
              <Text style={[style.muliExBoldDB, styles.instructionBoldText]}>
                {item?.boldSubtitle}
              </Text>
            </View>
          )}

          <View style={[styles.imageView]}>
            <Image
              source={item?.image}
              style={{
                width: "100%",
                height: "100%",
                aspectRatio: 1,
                alignSelf: "center",
                resizeMode: "contain",
              }}
            />
          </View>
          {/* info View */}
          <View style={styles.InfoView}>
            {/* <Text style={styles.headingText}>{translate(item.heading)}</Text> */}
            {item.subHeading && (
              <View>
                <Text style={styles.headingText}>{item.heading}</Text>
                {item.subHeading?.map((item, index) => {
                  return (
                    <View
                      key={"" + index}
                      style={{
                        flexDirection: "row",
                        alignItems: "flex-start",
                        marginVertical: 8,
                      }}
                    >
                      <Text key={"" + index} style={styles.pointStyle}>
                        {"\u2022"}
                      </Text>

                      <View>
                        <Text style={styles.pointText}>{"" + item.points}</Text>
                      </View>
                    </View>
                  );
                })}
              </View>
            )}
            {item?.boldSubtitle && (
              <View style={styles.instructionsContainer}>
                <Text style={[style.muliRegDB, styles.instructionText]}>
                  {item?.subtitle}
                </Text>
              </View>
            )}
          </View>
        </ScrollView>
        <View>
          <Pagination
            dotsLength={toturialData.length}
            activeDotIndex={index}
            containerStyle={{ alignContent: "flex-end" }}
            dotStyle={{
              width: 11,
              height: 6,
              borderRadius: 5,
              marginHorizontal: 6,
              backgroundColor: "#000000",
            }}
            inactiveDotStyle={{
              // Define styles for inactive dots here
              width: 6,
              height: 6,
              borderRadius: 5,
              marginHorizontal: 6,
              backgroundColor: "#DDDDDD",
            }}
            inactiveDotOpacity={0.4}
            inactiveDotScale={0.6}
          />
        </View>
      </View>
    );
  };
  return (
    <View style={styles.main}>
      <Spinner loading={isLoading} />
      <Header
        customTitle={"Quick Tips"}
        hideArrowBackButton={false}
        onlanguagechange={() => {
          forceUpdate();
        }}
        onbackPress={() => {
          if (navigation.canGoBack()) {
            navigation.pop();
          } else {
            if (Platform.OS === "android") {
              Alert.alert("Close", "are you sure ?", [
                {
                  text: "Yes",
                  onPress: () => {
                    BackHandler.exitApp();
                  },
                  style: "cancel",
                },
                {
                  text: "No",
                  onPress: () => {
                    console.log("on No pressed");
                  },
                },
              ]);
            }
          }
        }}
      />

      <View style={{ flex: 0.9 }}>
        <Carousel
          ref={nextcarousel}
          data={toturialData}
          renderItem={_renderToturial}
          sliderWidth={SCREEN_WIDTH}
          itemWidth={SCREEN_WIDTH}
          autoplay={false}
          loop={false}
          onBeforeSnapToItem={(index) => {
            SetCurrentIndex(index);
          }}
        />
      </View>
      <View
        style={{
          marginLeft: 24,
          marginRight: 24,
          width: SCREEN_WIDTH - 48,
          height: 1,
          backgroundColor: "#F5F5F5",
        }}
      />
      {currentIndex == toturialData.length - 1 ? (
        <View
          style={{
            flex: 0.1,
            justifyContent: "center",
            marginLeft: 24,
            marginRight: 24,
          }}
        >
          <PrimaryButton
            onPress={() => {
              if (instuction === undefined || instuction.length <= 0) {
                Alert.alert(
                  "Oops! ",
                  "We are unable to fetch guiding instruction for you, please try again"
                );
                if (navigation.canGoBack()) {
                  navigation.pop();
                } else {
                  /* handled crashed on OEM dealer */
                  if (route.params.props.navigation.canGoBack()) {
                    route.params.props.navigation.goBack();
                  }
                }
                return;
              }

              nextcarousel.current.snapToNext();
              if (currentIndex == toturialData.length - 1) {
                // startCapturingSensorData();

                /*@OLDFLOW */
                console.log("^^^^^^^^ ACTIVITYTYPEID", activityTypeId);
                if (canGoVideoPi(activityTypeId)) {
                  // UELogEvent("Toturial, starting VideoPI flow");
                  moveToRCBPreview();
                } else {
                  // UELogEvent("Starting Old flow.")
                  navigation.navigate("PI", {
                    activityId,
                    activityTypeId,
                    licensePlateNumber,
                  });
                }
              }
              Orientation.lockToLandscape();
            }}
          >
            {"I understand"}
          </PrimaryButton>
        </View>
      ) : (
        <View style={styles.buttonView}>
          {false && (
            <View style={{ flex: 0.5, justifyContent: "center" }}>
              <TouchableOpacity
                onPress={() => {
                  console.log("**** instuction " + instuction.length);

                  if (instuction === undefined || instuction.length <= 0) {
                    Alert.alert(
                      "Oops! ",
                      "We are unable to fetch guiding instruction for you, please try again"
                    );
                    console.log("^^^ Toturial -> Alert go back");
                    if (navigation.canGoBack()) {
                      navigation.pop();
                    } else {
                      /* handled crashed on OEM dealer */
                      if (route.params.props.navigation.canGoBack()) {
                        route.params.props.navigation.goBack();
                      }
                    }
                    return;
                  }

                  // startCapturingSensorData();
                  /*@OLDFLOW */
                  console.log(
                    "^^^^^^^ ACTIVITY TYPE ID ^^^^^^^^",
                    activityTypeId
                  );
                  if (canGoVideoPi(activityTypeId)) {
                    moveToRCBPreview();
                  } else {
                    navigation.navigate("PI", {
                      activityId,
                      activityTypeId,
                      licensePlateNumber,
                    });
                  }
                  Orientation.lockToLandscapeLeft();
                  firebaseEvents(
                    "skip_Tutorial_clicked",
                    "",
                    activityId,
                    activityTypeId,
                    ""
                  );
                }}
              >
                <Text
                  style={{
                    fontFamily: "Muli-Black",
                    fontSize: 14,
                    color: "#FFAA00",
                    alignSelf: "center",
                  }}
                >
                  {translate("SKIP TUTORIAL")}
                </Text>
              </TouchableOpacity>
            </View>
          )}
          <View style={{ flex: 1, justifyContent: "center" }}>
            <PrimaryButton
              onPress={() => {
                if (instuction === undefined || instuction.length <= 0) {
                  Alert.alert(
                    "Oops! ",
                    "We are unable to fetch guiding instruction for you, please try again"
                  );
                  if (navigation.canGoBack()) {
                    navigation.pop();
                  } else {
                    /* handled crashed on OEM dealer */
                    if (route.params.props.navigation.canGoBack()) {
                      route.params.props.navigation.goBack();
                    }
                  }
                  return;
                }

                nextcarousel.current.snapToNext();
                if (currentIndex == toturialData.length - 1) {
                  // startCapturingSensorData();
                  moveToCamera(true);
                  Orientation.lockToLandscapeLeft();
                  firebaseEvents(
                    "start_clicked",
                    "",
                    activityId,
                    activityTypeId,
                    ""
                  );
                }
              }}
            >
              {currentIndex == toturialData.length - 1
                ? translate("Start")
                : translate("Next")}
            </PrimaryButton>
          </View>
        </View>
      )}
    </View>
  );
};
export default Toturial;

const styles = StyleSheet.create({
  main: {
    flex: 1,
    backgroundColor: "#FFFFFF",
  },
  imageView: {
    flex: 0.6,
    justifyContent: "center",
  },
  InfoView: {
    flex: 0.4,
  },
  headingText: {
    fontFamily: "Muli-Bold",
    fontSize: 20,
    marginBottom: 16,
  },
  pointText: {
    fontSize: 18,
    fontFamily: "Muli-Regular",
    lineHeight: 30,
    paddingHorizontal: 8,
  },
  buttonView: {
    flex: 0.1,
    marginLeft: 24,
    marginRight: 24,
    justifyContent: "center",
    flexDirection: "row",
  },
  pointStyle: {
    fontSize: 18,
    fontFamily: "Muli-Regular",
    lineHeight: 30,
    color: Colors.veryLightGray,
  },
  instructionsContainer: {
    flex: 0.2,
    justifyContent: "space-evenly",
    alignItems: "center",
    marginTop: 30,
    paddingVertical: 8,
  },
  instructionText: {
    fontSize: 18,
    textAlign: "center",
    lineHeight: 18,
  },
  instructionBoldText: {
    fontSize: 18,
    lineHeight: 22,
  },
  yellowLine: {
    height: 3,
    width: 35,
    backgroundColor: Colors.digitYellow,
    position: "absolute",
    bottom: -5,
    borderRadius: 3,
  },
});
