import React, { useEffect, useRef, useState } from "react";
import {
  StyleSheet,
  View,
  Image,
  Text,
  Platform,
  Linking,
  FlatList,
  Alert,
} from "react-native";
import BoldText from "../common/BoldText";

import {
  ANDROID_REQUEST,
  canGoVideoPi,
  WEB_REQUEST,
  is2Wflow,
  shouldWatchDemoVideo,
} from "react-native-digitcamera/src/common/Constants";
import {
  UELogEvent,
  UELogMessage,
} from "../common/libEventLog/UserExperior/LibUserExperior";
import { Dynatrace } from "@dynatrace/react-native-plugin";
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 { useIsAppForeground } from "../common/useIsForeground";
import Header from "../Screens/Header";
import InIcon from "react-native-vector-icons/Ionicons";
import { PrimaryButton, Spinner } from "../common/ThemedComponents";
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";
import { checkHardwareAvailableForML } from "react-native-digitcamera/src/common/CheckHardwareML";
import { useIsFocused } from "@react-navigation/native";

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 Colors from "react-native-digitcamera/src/common/Colors";

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

import Database from "../../../../Components/common/DAsyncStorage";
import { getAndroidPermission } from "../common/Permissions";
import getConfig from "../common/remote_config/FirebaseConfig";
import { FIREBASE_CONFIG_CONFIDENCE } from "react-native-digitcamera/src/Screens/ProcessRawOutput";

import {
  getMaxWidth,
  getMinWidth,
} from "../../../../Components/common/scaling";
import { checkInternetSpeed } from "react-native-digitcamera/src/Screens/OfflineFlow/CommonFunc";

const QUICK_TIP_TYPE = {
  GUIDE: "GUIDE",
  RCB: "RCB",
};
let rcbObj;
var isFocussed;

const TipCard = (item) => {
  console.log("item?.quickTipType", item?.quickTipType);
  if (item?.quickTipType === QUICK_TIP_TYPE.RCB) {
    return (
      <View style={styles.TipCardContainer}>
        <View style={styles.TipCardRCBMain}>
          <View style={{ flex: 0.49, paddingTop: 8 }}>
            <Image
              key={item?.instructionAssests}
              source={{
                uri: item?.instructionAssests,
                cache: "only-if-cached",
              }}
              style={styles.QTImage}
            />
          </View>
          <View
            style={[
              {
                flex: 0.49,
                justifyContent: "center",
              },
            ]}
          >
            <Text style={styles.TipCardRCBTitle}>{item?.instructionData}</Text>
          </View>
        </View>
      </View>
    );
  }

  // FOR QUICK TIP TYPE : GUIDE

  return (
    <View style={styles.TipCardContainer}>
      <BoldText
        key={item}
        style={[style.muliRegDB, styles.QTBoldText]}
        text={item?.instructionData}
        boldTextColor={Colors.darkBlack}
        boldTextStyle={{ fontSize: 18 }}
      />
      <View style={styles.TipCardGuideMain}>
        {/* Correct */}
        <View
          style={{
            flex: 0.49,
            borderWidth: 1.5,
            borderColor: Colors.borderBlack,
            borderRadius: 6,
          }}
        >
          <View style={{ position: "absolute", zIndex: 1, right: 0 }}>
            <View style={[styles.QTIconView, { backgroundColor: "#00AA55" }]}>
              <InIcon name="checkmark-sharp" size={28} color={"white"} />
            </View>
          </View>
          <Image
            key="fsdfsd"
            source={{
              uri: item?.tInstructionMandate[0]?.link,
            }}
            style={styles.QTImage}
            resizeMode="contain"
          />
        </View>
        {/* Incorrect */}
        <View
          style={{
            flex: 0.49,
            borderWidth: 1.5,
            borderColor: Colors.borderBlack,
            borderRadius: 6,
          }}
        >
          <View style={{ position: "absolute", zIndex: 1, right: 0 }}>
            <View style={[styles.QTIconView, { backgroundColor: "#EE0000" }]}>
              <InIcon
                name="close-sharp"
                size={28}
                color={"white"}
                style={{ marginLeft: 2 }}
              />
            </View>
          </View>
          <Image
            source={{
              uri: item?.tInstructionMandate[1]?.link,
            }}
            style={styles.QTImage}
            resizeMode="contain"
          />
        </View>
      </View>
    </View>
  );
};

// Fetch vehcile instruction one time
const QuickTips = ({ navigation, route }) => {
  isFocussed = useIsFocused();
  const nextcarousel = React.createRef();
  const [currentIndex, setCurrentIndex] = useState(0);
  const [QuickTipsData, setQuickTipsData] = useState([]);
  const [isInternetConnected, setIsInternetConnected] = useState(true);

  const handleContinue = async () => {
    if (Platform.OS === "android") {
      /*

      await getAndroidPermission(onGranted, onRejected)

      onGranted: if all the permissions are granted
      onRejected: any one of the permission is rejected

      */

      await getAndroidPermission(
        () => {
          moveNow();
        },
        async () => {
          await Linking.openSettings();
        }
      );
    } else {
      moveNow();
    }
  };

  const moveNow = async () => {
    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;
    // If RCB is asked take user to RCBPreviewScreen
    // if (rcbObj) {
    //   navigation.navigate("RCBPreviewScreen");
    // } else {
    console.log("isInternetConnected", isInternetConnected);
    if (isInternetConnected) {
      const { ml_pose, ml_confidence, ml_OS_version, ml_RAM } =
        await getConfig();
      var mlHardwareAvailable = await checkHardwareAvailableForML(
        ml_OS_version,
        ml_RAM
      );
      // we have to check internet for getConfig function
      console.log(
        "[Info] . Quick Tips . moveNow() . instuction - ",
        instuction
      );

      FIREBASE_CONFIG_CONFIDENCE.value = ml_confidence;
      console.log(
        "checkHardwareAvailableForML mlHardwareAvailable ",
        mlHardwareAvailable
      );
      console.log(
        "[Info] . Quick Tips . mlHardwareAvailable, ml_pose ",
        mlHardwareAvailable,
        ml_pose
      );
      UELogEvent("ml_pose", {
        value: ml_pose,
      });
      UELogEvent("mlHardwareAvailable", {
        value: mlHardwareAvailable,
      });
      Dynatrace.enterAction("ml_pose: " + ml_pose, Platform.OS);
      Dynatrace.enterAction(
        "mlHardwareAvailable: " + mlHardwareAvailable,
        Platform.OS
      );
      mlHardwareAvailable = mlHardwareAvailable && ml_pose;
      UELogEvent("Machine Learning", {
        value: mlHardwareAvailable,
      });
      Dynatrace.enterAction(
        "Machine Learning: " + mlHardwareAvailable,
        Platform.OS
      );
      navigation.navigate("Camera", {
        activityId,
        activityTypeId,
        licensePlateNumber,
        toVDO: true, //always true in this case
        instruction: instuction,
        mlHardwareAvailable,
      });
    } else {
      navigation.navigate("Camera", {
        activityId,
        activityTypeId,
        licensePlateNumber,
        toVDO: true, //always true in this case
        instruction: instuction,
        mlHardwareAvailable: false,
      });
    }

    // }
  };

  const flatListRef = useRef(null);

  const handleOnNext = () => {
    if (currentIndex === QuickTipsData.length - 1) {
      handleContinue();
      return;
    }
    setCurrentIndex(currentIndex + 1);
  };

  const handleOnPrev = () => {
    if (currentIndex === 0) return;
    setCurrentIndex(currentIndex - 1);
  };

  const onLayout = () => {
    flatListRef.current?.scrollToIndex({
      animated: true,
      index: 0,
      viewPosition: 0.5,
    });
  };

  const getQuicktipData = async () => {
    // 1) get data from Db
    // 2) check if RCB is present or not, According to that manage navigations on the screen to recording screen
    var PIVechicleInstruction = await Database.get("PIVechicleInstruction");
    var instructionArr = JSON.parse(PIVechicleInstruction?.instuction);
    let item = instructionArr.find((item) => item.imageName === "VDO");
    rcbObj = instructionArr.find((element) => {
      return element.imageName.includes("RCB");
    });

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

        const onlyGuideQuickTips = imageTypeInstructions.filter(
          (item) => item.quickTipType === "GUIDE"
        );

        setQuickTipsData(onlyGuideQuickTips);
      }
    }
  };

  useEffect(async () => {
    // this is for quickTips dynamic data
    await getQuicktipData();
    const unsubscribeNetInfo = NetInfo.addEventListener(async (state) => {
      if (state.isInternetReachable != null && isFocussed) {
        if (state.isInternetReachable && (await checkInternetSpeed())) {
          setIsInternetConnected(true);
        } else {
          setIsInternetConnected(false);
          UELogEvent("Offline Flow : QuickTips.js", { mode: "offline" });
        }
      }
    });

    return () => {
      unsubscribeNetInfo && unsubscribeNetInfo();
    };
  }, []);

  useEffect(async () => {
    flatListRef.current.scrollToIndex({
      animated: true,
      index: currentIndex,
      viewOffset: 0,
      viewPosition: 0.5,
    });
  }, [currentIndex]);

  return (
    <View style={styles.main}>
      <Header
        customTitle={`Necessary Instructions`}
        showOnlySteps={true}
        currentOnlyStep={currentIndex + 1}
        totalOnlyStep={QuickTipsData.length}
        hideArrowBackButton={false}
        onlanguagechange={() => {
          forceUpdate();
        }}
        onbackPress={() => {
          if (currentIndex === 0) {
            if (navigation.canGoBack()) {
              navigation.pop();
            }
          } else {
            setCurrentIndex(currentIndex - 1);
          }
        }}
      />

      <View style={styles.QTMainView}>
        <View
          style={{
            flex: 0.8,
          }}
        >
          {QuickTipsData.length > 0 && (
            <FlatList
              initialScrollIndex={0}
              onLayout={onLayout}
              data={QuickTipsData}
              keyExtractor={(item) => item.title}
              renderItem={({ item }) => <TipCard {...item} />}
              showsHorizontalScrollIndicator={false}
              horizontal
              pagingEnabled
              ref={flatListRef}
              scrollEnabled={false}
              contentContainerStyle={{}}
            />
          )}
        </View>
        <View style={styles.QTButtonView}>
          {currentIndex !== 0 && (
            <PrimaryButton
              style={{
                width: 150,
                marginRight: 8,
              }}
              onPress={handleOnPrev}
              mode={"outlined"}
            >
              Previous
            </PrimaryButton>
          )}
          <PrimaryButton
            style={{
              minWidth: 200,
            }}
            onPress={handleOnNext}
          >
            {currentIndex === QuickTipsData.length - 1
              ? "Start Recording"
              : "Next"}
          </PrimaryButton>
        </View>
      </View>
    </View>
  );
};
export default QuickTips;

let SCREEN_WIDTH = getMaxWidth();
let SCREEN_HEIGHT = getMinWidth();

const styles = StyleSheet.create({
  main: {
    flex: 1,
    backgroundColor: "#FFFFFF",
  },
  QTMainView: {
    flex: 1,
    paddingLeft: 32,
    paddingRight: 16,
    justifyContent: "space-between",
  },
  QTIconView: {
    width: 42,
    height: 42,
    borderRadius: 250,
    justifyContent: "center",
    alignItems: "center",
    marginRight: 8,
    marginTop: 8,
  },
  QTImage: {
    height: "100%",
    width: "100%",
    borderRadius: 8,
    resizeMode: "cover",
  },
  QTImageRCB: {
    height: "100%",
    width: "100%",
    borderRadius: 8,
    resizeMode: "cover",
  },
  QTButtonView: {
    flex: 0.2,
    justifyContent: "flex-end",
    alignItems: "center",
    flexDirection: "row",
    // marginBottom: 8,
  },
  QTBoldText: {
    marginBottom: 8,
    fontSize: 18,
    marginHorizontal: 0,
  },
  TipCardContainer: {
    flex: 1,
    height: SCREEN_WIDTH * 0.3,
    width: SCREEN_WIDTH * 0.95,
    marginHorizontal: 24,
    paddingHorizontal: 24,
    // backgroundColor: "grey",
  },
  TipCardRCBMain: {
    flex: 1,
    flexDirection: "row",
    justifyContent: "space-between",
  },
  TipCardGuideMain: {
    flex: 1,
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
  },
  TipCardRCBTitle: { fontSize: 20, fontFamily: "Muli-Bold", fontWeight: "700" },
  TipCardGuideTitle: {
    marginVertical: 8,
    fontWeight: "400",
    fontSize: 18,
    fontFamily: "Muli-Regular",
    color: "#000000",
  },
  muliBoldDB: {
    fontFamily: "Muli-Bold",
    color: Colors.darkBlack,
  },
});
