import React, { useEffect, useRef, useState } from "react";
import {
  StyleSheet,
  View,
  Image,
  Text,
  StatusBar,
  ScrollView,
} from "react-native";
import {
  SCREEN_HEIGHT,
  SCREEN_WIDTH,
} 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/Database";
let realm = Database.getRealm();
import { measureConnectionSpeed } from "react-native-network-bandwith-speed";
import {
  ANDROID_REQUEST,
  WEB_REQUEST,
} from "react-native-digitcamera/lib/commonjs/common/Constants";
import { instructionData } from "react-native-digitcamera/src/common/Services/instruction";
import { dispatch } from "react-native-digitcamera/src/common/RootNavigation";
import { BackHandler } from "react-native";
import { Alert } from "react-native";
import {
  firebaseAttributes,
  errorRecord,
  firebaseEvents,
} from "../common/libEventLog/libCrashlytics/libCrashlyticsEvent";
import { async } from "validate.js";
import {
  startCapturingSensorData,
  cleanSensorDataArr,
  unsubscribeSensors,
} from "../common/SensorData";

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 Toturial = ({ navigation, route }) => {
  const nextcarousel = useRef();
  const [currentIndex, SetCurrentIndex] = useState(0);
  const [isLoading, SetIsLoading] = useState(true);
  const [, updateState] = React.useState();
  const forceUpdate = React.useCallback(() => updateState({}), []);
  const toturialData = [
    {
      image: open_area_good_light,
      heading: "Before clicking the images, please make sure:",
      subHeading: [
        { points: "Your vechicle us 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 the vehicle Registration Certificate (RC Copy) 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: [],
    },
  ];
  var activityId,
    activityTypeId,
    licensePlateNumber,
    toWithQuote,
    toTutorial,
    quoteNumber;
  var DataSpeed;
  let instuction = [];

  useEffect(() => {
    Orientation.lockToPortrait();

    var RealmData = realm.objects("PIVechicleData");
    (activityId = RealmData[0].activityId),
      (activityTypeId = RealmData[0].activityTypeId),
      (licensePlateNumber = RealmData[0].licensePlateNumber),
      (toWithQuote = RealmData[0].toWithQuote),
      (toTutorial = RealmData[0].toTutorial),
      (quoteNumber = RealmData[0].quoteNumber),
      console.log(
        "!!!!!!!!!!!!!!!!!!!!!!!!",
        activityId,
        activityTypeId,
        licensePlateNumber,
        toWithQuote,
        toTutorial,
        quoteNumber
      );

    getInstruction();

    let unsubscribe = navigation.addListener("focus", () => {
      Orientation.lockToPortrait();
    });
    saveToRealm();
    firebaseAttributes();
    return () => {
      unsubscribe();
      cleanSensorDataArr();
      unsubscribeSensors();
    };
  }, []);

  const saveToRealm = () => {
    try {
      realm.write(() => {
        realm.delete(realm.objects("PIRCBCount"));

        realm.create("PIRCBCount", {
          addMoreCount: 2,
        });
      });

      realm.write(() => {
        realm.delete(realm.objects("PIclickedCount"));

        realm.create("PIclickedCount", {
          clickedCount: 0,
        });
      });

      realm.write(() => {
        realm.delete(realm.objects("PIUploadedCount"));

        realm.create("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 = () => {};

  // get vechicle instructions
  const getInstruction = async () => {
    try {
      let requestTypeName = 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 (true) {
        // if (false) {
        instuction = [];
        V_instuction?.TSurveySteps.map((item) => {
          instuction.push(item);
        });
      } else {
        instuction = [];
        V_instuction?.TSurveySteps.map((item) => {
          if (item.imageName != "VDO") {
            instuction.push(item);
          }
        });
      }
      // sorting instructions
      instuction.sort((obj1, obj2) => {
        let id1 = obj1.displayOrder;
        let id2 = obj2.displayOrder;
        return id1 - id2;
      });

      realm.write(() => {
        realm.delete(realm.objects("PIVechicleInstruction"));
        realm.create("PIVechicleInstruction", {
          instuction: JSON.stringify(instuction),
        });
        var RealmInstructionData = realm.objects("PIVechicleInstruction");
        console.log(
          "^^^^^^^^^^^^^^^^^^^^^^^^^ ",
          JSON.parse(RealmInstructionData[0].instuction).length
        );
      });
      SetIsLoading(false);
      firebaseEvents(
        "Instruction",
        { requestTypeValue: requestTypeValue },
        activityId,
        activityTypeId,
        ""
      );
    } catch (error) {
      firebaseAttributes(error);
      errorRecord(error);
      console.log("Error in Tutorial >>> ", error);
      Alert.alert("Please try again !!!");
      SetIsLoading(false);
    }
  };

  const _renderToturial = ({ item, index }) => {
    return (
      <View style={{ margin: 24, flex: 1 }}>
        <ScrollView>
          {/* Image view */}
          <View style={styles.imageView}>
            <Image
              source={item.image}
              resizeMode="contain"
              style={{
                width: SCREEN_WIDTH - 100,
                height: SCREEN_WIDTH / 1.47,
                alignSelf: "center",
                resizeMode: "contain",
              }}
            />
          </View>
          {/* info View */}
          <View style={styles.InfoView}>
            <Text style={styles.headingText}>{translate(item.heading)}</Text>
            {item.subHeading?.map((item, index) => {
              return (
                <Text key={"" + index} style={styles.pointText}>
                  {"\u2022"}
                  {" " + translate(item.points)}
                </Text>
              );
            })}
          </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
        hideArrowBackButton={false}
        onlanguagechange={() => {
          forceUpdate();
        }}
        onbackPress={() => {
          try {
            console.log("navigation.canGoBack()", navigation.canGoBack());
            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");
                    },
                  },
                ]);
              }
            }
          } catch (error) {}
        }}
      />

      <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 == 3 ? (
        <View
          style={{
            flex: 0.1,
            justifyContent: "center",
            marginLeft: 24,
            marginRight: 24,
          }}
        >
          <PrimaryButton
            onPress={() => {
              nextcarousel.current.snapToNext();
              if (currentIndex == 3) {
                startCapturingSensorData();
                navigation.navigate("PI", {
                  activityId,
                  activityTypeId,
                  licensePlateNumber,
                });
              }
              Orientation.lockToLandscapeLeft();
            }}
          >
            {translate("Start")}
          </PrimaryButton>
        </View>
      ) : (
        <View style={styles.buttonView}>
          <View style={{ flex: 0.5, justifyContent: "center" }}>
            <TouchableOpacity
              onPress={() => {
                startCapturingSensorData();
                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: 0.5, justifyContent: "center" }}>
            <PrimaryButton
              onPress={() => {
                nextcarousel.current.snapToNext();
                if (currentIndex == 3) {
                  startCapturingSensorData();
                  navigation.navigate("PI", {
                    activityId,
                    activityTypeId,
                    licensePlateNumber,
                  });
                  Orientation.lockToLandscapeLeft();
                  firebaseEvents(
                    "start_clicked",
                    "",
                    activityId,
                    activityTypeId,
                    ""
                  );
                }
              }}
            >
              {currentIndex == 3 ? 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,
    marginTop: 24,
  },
  pointText: {
    fontSize: 18,
    fontFamily: "Muli-Regular",
    lineHeight: 30,
  },
  buttonView: {
    flex: 0.1,
    marginLeft: 24,
    marginRight: 24,
    justifyContent: "center",
    flexDirection: "row",
    marginBottom: 24,
  },
});
