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";
import store from "react-native-digitcamera/src/redux/store";
import {
  car_10ft,
  car_arch,
  car_nonarch,
  car_dirty,
  car_driver,
  car_frontview,
  car_mobile,
  car_parking,
  car_passenger,
  car_clean,
} from "../common/Assets";
import { useSelector } from "react-redux";

const offlineGuideData = [
  {
    surveyInstructionsId: 2110,
    createdDate: "Oct 20, 2022 12:04:28 PM",
    instructionData: "Park in an <b>Open Well-lit</b> area",
    lastModifiedDate: "Oct 25, 2022 01:04:53 PM",
    instructionTime: 2,
    displayOrder: 16,
    type: "image",
    quickTipType: "GUIDE",
    effectiveDate: "Oct 20, 2022 12:04:28 PM",
    instructionTitle: "Quick Tips",
    instructionAssests: "",
    tInstructionMandate: [
      {
        mandateId: 1,
        createdDate: "Oct 25, 2022 12:37:18 PM",
        lastModifiedDate: "Oct 25, 2022 12:37:18 PM",
        link: "https://d2h44aw7l5xdvz.cloudfront.net/CRM/PRM/1-07.png",
        mandateType: "DO",
      },
      {
        mandateId: 2,
        createdDate: "Oct 25, 2022 12:37:18 PM",
        lastModifiedDate: "Oct 25, 2022 12:37:18 PM",
        link: "https://d2h44aw7l5xdvz.cloudfront.net/CRM/PRM/1-08.png",
        mandateType: "DONT",
      },
    ],
  },
  {
    surveyInstructionsId: 2112,
    createdDate: "Oct 20, 2022 12:04:28 PM",
    instructionData: "Leave <b>10ft Space</b> on all sides",
    lastModifiedDate: "Oct 25, 2022 01:04:53 PM",
    instructionTime: 2,
    displayOrder: 17,
    type: "image",
    quickTipType: "GUIDE",
    effectiveDate: "Oct 20, 2022 12:04:28 PM",
    instructionTitle: "Quick Tips",
    instructionAssests: "",
    tInstructionMandate: [
      {
        mandateId: 3,
        createdDate: "Oct 25, 2022 12:37:18 PM",
        lastModifiedDate: "Oct 25, 2022 12:37:18 PM",
        link: "https://d2h44aw7l5xdvz.cloudfront.net/CRM/PRM/1-03.png",
        mandateType: "DO",
      },
      {
        mandateId: 4,
        createdDate: "Oct 25, 2022 12:37:18 PM",
        lastModifiedDate: "Oct 25, 2022 12:37:18 PM",
        link: "https://d2h44aw7l5xdvz.cloudfront.net/CRM/PRM/1-04.png",
        mandateType: "DONT",
      },
    ],
  },
  {
    surveyInstructionsId: 2114,
    createdDate: "Oct 20, 2022 12:04:28 PM",
    instructionData: "<b>Wipe & Clean</b> your car",
    lastModifiedDate: "Oct 25, 2022 01:04:53 PM",
    instructionTime: 2,
    displayOrder: 18,
    type: "image",
    quickTipType: "GUIDE",
    effectiveDate: "Oct 20, 2022 12:04:28 PM",
    instructionTitle: "Quick Tips",
    instructionAssests: "",
    tInstructionMandate: [
      {
        mandateId: 5,
        createdDate: "Oct 25, 2022 12:37:18 PM",
        lastModifiedDate: "Oct 25, 2022 12:37:18 PM",
        link: "https://d2h44aw7l5xdvz.cloudfront.net/CRM/PRM/1-05.png",
        mandateType: "DO",
      },
      {
        mandateId: 6,
        createdDate: "Oct 25, 2022 12:37:18 PM",
        lastModifiedDate: "Oct 25, 2022 12:37:18 PM",
        link: "https://d2h44aw7l5xdvz.cloudfront.net/CRM/PRM/1-06.png",
        mandateType: "DONT",
      },
    ],
  },
  {
    surveyInstructionsId: 2116,
    createdDate: "Oct 20, 2022 12:04:28 PM",
    instructionData: "Keep <b>Full Car</b> in focus during the video shoot",
    lastModifiedDate: "Oct 25, 2022 01:04:53 PM",
    instructionTime: 2,
    displayOrder: 19,
    type: "image",
    quickTipType: "GUIDE",
    effectiveDate: "Oct 20, 2022 12:04:28 PM",
    instructionTitle: "Quick Tips",
    instructionAssests: "",
    tInstructionMandate: [
      {
        mandateId: 7,
        createdDate: "Oct 25, 2022 12:37:18 PM",
        lastModifiedDate: "Oct 25, 2022 12:37:18 PM",
        link: "https://d2h44aw7l5xdvz.cloudfront.net/CRM/PRM/1-01.png",
        mandateType: "DO",
      },
      {
        mandateId: 8,
        createdDate: "Oct 25, 2022 12:37:18 PM",
        lastModifiedDate: "Oct 25, 2022 12:37:18 PM",
        link: "https://d2h44aw7l5xdvz.cloudfront.net/CRM/PRM/1-02.png",
        mandateType: "DONT",
      },
    ],
  },
];

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

const TipCard = (item) => {
  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,
            },
            item?.isInternetReachable ? styles.borderView : {},
          ]}
        >
          <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={item?.tInstructionMandate[0]?.link}
            style={styles.QTImage}
            resizeMode="contain"
          />
        </View>
        {/* Incorrect */}
        <View
          style={[
            {
              flex: 0.49,
            },
            item?.isInternetReachable ? styles.borderView : {},
          ]}
        >
          <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={item?.tInstructionMandate[1]?.link}
            style={styles.QTImage}
            resizeMode="contain"
          />
        </View>
      </View>
    </View>
  );
};

const getImageByData = (data) => {
  switch (data) {
    case "Park in an <b>Open Well-lit</b> area":
      return [car_nonarch, car_arch];
    case "Leave <b>10ft Space</b> on all sides":
      return [car_10ft, car_parking];
    case "<b>Wipe & Clean</b> your car":
      return [car_clean, car_dirty];
    case "Keep <b>Full Car</b> in focus during the video shoot":
      return [car_mobile, car_frontview];
  }
};

const generateQuickTips = (data, internetReachable) => {
  const modifiedData = data.map((item) => {
    const instructionData = item.instructionData;
    const tInstructionMandate = item.tInstructionMandate;
    if (internetReachable) {
      const tInstructionMandateModified = tInstructionMandate.map(
        (instruction) => {
          const link = instruction.link;
          return { ...instruction, link: { uri: link } };
        }
      );
      return {
        ...item,
        tInstructionMandate: tInstructionMandateModified,
      };
    } else {
      const tInstructionMandateModified = tInstructionMandate.map(
        (instruction) => {
          const mandateType = instruction.mandateType;
          const imageData = getImageByData(instructionData);
          return {
            ...instruction,
            link: mandateType === "DO" ? imageData[0] : imageData[1],
          };
        }
      );
      return {
        ...item,
        tInstructionMandate: tInstructionMandateModified,
      };
    }
  });
  return modifiedData;
};

const QuickTips = ({ navigation, route }) => {
  isFocussed = useIsFocused();
  const nextcarousel = React.createRef();
  const [currentIndex, setCurrentIndex] = useState(0);
  const [QuickTipsData, setQuickTipsData] = useState([]);
  const { isInternetReachable } = useSelector((state) => state.network);

  useEffect(() => {
    Orientation.lockToLandscape();
  });

  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;

    console.log("isInternetConnected", isInternetReachable);
    if (isInternetReachable) {
      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
      );
      // mlHardwareAvailable = true;
      navigation.navigate("Camera", {
        activityId,
        activityTypeId,
        licensePlateNumber,
        toVDO: true, //always true in this case
        instruction: instuction,
        mlHardwareAvailable,
      });
    } else {
      // mlHardwareAvailable = true;

      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"
        );

        if (onlyGuideQuickTips.length === 0) {
          const quickTipsData = generateQuickTips(
            offlineGuideData,
            isInternetReachable
          );
          setQuickTipsData(quickTipsData);
        } else {
          const quickTipsData = generateQuickTips(
            onlyGuideQuickTips,
            isInternetReachable
          );
          setQuickTipsData(quickTipsData);
        }
      }
    }
  };

  useEffect(() => {
    if (isInternetReachable === true) {
      getQuicktipData();
    } else if (isInternetReachable === false) {
      getQuicktipData();
    }
  }, [isInternetReachable]);

  useEffect(() => {
    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,
            alignItems: "center",
          }}
        >
          {QuickTipsData.length > 0 && (
            <FlatList
              initialScrollIndex={0}
              onLayout={onLayout}
              data={QuickTipsData}
              keyExtractor={(item) => item.title}
              renderItem={({ item }) => (
                <TipCard {...item} isInternetReachable={isInternetReachable} />
              )}
              showsHorizontalScrollIndicator={false}
              horizontal
              pagingEnabled
              ref={flatListRef}
              scrollEnabled={false}
              style={{ width: SCREEN_WIDTH * 0.9 }}
              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: 36,
    height: 36,
    borderRadius: 250,
    justifyContent: "center",
    alignItems: "center",
    marginRight: 8,
    marginTop: 24,
  },
  QTImage: {
    height: "100%",
    width: "100%",
  },
  QTImageRCB: {
    height: "100%",
    width: "100%",
  },
  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.85,
    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,
  },
  borderView: {
    borderWidth: 1.5,
    borderColor: Colors.borderBlack,
    borderRadius: 6,
  },
});
