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 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 {
  firebaseAttributes,
  errorRecord,
  firebaseEvents,
} from "../common/libEventLog/libCrashlytics/libCrashlyticsEvent";

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

const open_area_good_light = require("../common/Image/open_area_good_light.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";

import {
  UELogEvent,
  UELogMessage,
} from "../common/libEventLog/UserExperior/LibUserExperior";
import Colors from "react-native-digitcamera/src/common/Colors";

import style from "../../../../Components/common/CommonStyle";

import { SCREEN_WIDTH } from "react-native-digitcamera/src/common/Constants";

import Database from "../../../../Components/common/DAsyncStorage";

const VIDEOPI_POINTS = [
  {
    image: open_area_good_light,
    heading: "Before shooting the video: ",
    subHeading: [
      { points: "Park the car in a well-lit area" },
      { points: "Wipe & clean your car" },
    ],
  },
  {
    image: { uri: horizontalModePhone },
    heading: "While shooting the video ",
    subHeading: [
      {
        points: "Keep your phone in landscape mode",
      },
      { points: "Camera should be stable" },
      { points: "Full car should be visible on the screen" },
    ],
  },
  {
    image: { uri: vehicle10ft },
    subtitle: "Stand 10 ft away from your car",
    boldSubtitle: "10 ft of space",
  },
];

// When this (QuickTips.js) should render
// 1. From DemoVideo only

const QuickTips = ({ navigation, route }) => {
  const nextcarousel = React.createRef();
  const [currentIndex, SetCurrentIndex] = useState(0);

  const { withoutRCB } = route.params;

  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 = async (toVDO) => {
    const PIVechicleData = await Database.get("PIVechicleData");
    const activityId = PIVechicleData?.activityId;
    const activityTypeId = PIVechicleData?.activityTypeId;
    const licensePlateNumber = PIVechicleData?.licensePlateNumber;

    const PIVechicleInstruction = await Database.get("PIVechicleInstruction");
    const instuction = PIVechicleInstruction?.instuction;

    console.log("[Info] . Quick Tips . moveNow() . instuction - ", instuction);
    const mlHardwareAvailable = await checkHardwareAvailableForML();
    console.log(
      "[Info] . Quick Tips . mlHardwareAvailable - ",
      mlHardwareAvailable
    );
    navigation.navigate("Camera", {
      activityId,
      activityTypeId,
      licensePlateNumber,
      toVDO: toVDO,
      instruction: instuction,
      mlHardwareAvailable,
    });
  };

  const _renderToturial = ({ item, index }) => {
    return (
      <View style={{ margin: 24, flex: 1 }}>
        <ScrollView>
          {/* Image view */}

          {item?.boldSubtitle && (
            <View
              style={{
                flexDirection: "row",
                marginVertical: 16,
                alignSelf: "center",
              }}
            >
              <View style={styles.yellowLine}></View>
              <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={VIDEOPI_POINTS.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}>
      <Header
        customTitle={"Quick Tips"}
        hideArrowBackButton={false}
        onlanguagechange={() => {
          forceUpdate();
        }}
        onbackPress={() => {
          if (withoutRCB) {
            navigation.navigate("WithQuote");
          }
          if (navigation.canGoBack()) {
            navigation.pop();
            Orientation.lockToLandscapeLeft();
          }
        }}
      />

      <View style={{ flex: 0.9 }}>
        <Carousel
          ref={nextcarousel}
          data={VIDEOPI_POINTS}
          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 == VIDEOPI_POINTS.length - 1 ? (
        <View
          style={{
            flex: 0.1,
            justifyContent: "center",
            marginLeft: 24,
            marginRight: 24,
          }}
        >
          <PrimaryButton
            onPress={() => {
              nextcarousel.current.snapToNext();
              if (currentIndex == VIDEOPI_POINTS.length - 1) {
                startCapturingSensorData();
                moveToCamera(true);
              }

              // Orientation.lockToLandscape();
            }}
          >
            {"I understand"}
          </PrimaryButton>
        </View>
      ) : (
        <View style={styles.buttonView}>
          <View style={{ flex: 1, justifyContent: "center" }}>
            <PrimaryButton
              onPress={() => {
                nextcarousel.current.snapToNext();
                if (currentIndex == VIDEOPI_POINTS.length - 1) {
                  startCapturingSensorData();
                  moveToCamera(true);
                  // Orientation.lockToLandscapeLeft();
                  // firebaseEvents(
                  //     "start_clicked",
                  //     "",
                  //     activityId,
                  //     activityTypeId,
                  //     ""
                  // );
                }
              }}
            >
              {currentIndex == VIDEOPI_POINTS.length - 1
                ? translate("Start")
                : translate("Next")}
            </PrimaryButton>
          </View>
        </View>
      )}
    </View>
  );
};
export default QuickTips;

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