import React, { useEffect, useRef, useState } from "react";
const iOS = Platform.OS === "ios";
import {
  BackHandler,
  Image,
  Platform,
  StatusBar,
  StyleSheet,
  Text,
  View,
  Alert,
  ScrollView,
  KeyboardAvoidingView,
} from "react-native";
import Colors from "react-native-digitcamera/src/common/Colors";
import { SafeAreaView } from "react-native-safe-area-context";
import Database from "../../../../Components/common/DAsyncStorage";
import Orientation from "react-native-orientation";
/*@RCBPREVIEW*/
import { useDispatch } from "react-redux";
import {
  Ibutton,
  Spinner,
} from "react-native-digitcamera/src/common/ThemedComponents";
import { SCREEN_HEIGHT } from "../../../../Components/common/Constants";
import {
  PrimaryButton,
  TextInput,
} from "../../../../Components/common/ThemedComponents";
import {
  UELogEvent,
  UELogMessage,
} from "../common/libEventLog/UserExperior/LibUserExperior";
import NetInfo from "@react-native-community/netinfo";
import { useMemo } from "react";
import { CreateActivityId } from "react-native-digitcamera/src/Screens/OfflineFlow/CreateActivityId";
import { renderErrorMsge } from "react-native-digitcamera/src/common/Validation";
import style from "react-native-digitcamera/src/common/CommonStyle";

const Odometer = ({ navigation, route }) => {
  const [odometerReadings, setOdometerReadings] = useState("");
  const [, updateState] = React.useState();
  const [OdometerInstructionData, setOdometerInstructionData] = useState();
  const forceUpdate = React.useCallback(() => updateState({}), []);
  const [internetAvailable, setInternetAvailable] = useState(false);
  const [loading, setIsLoading] = useState(false);

  /*@RCBPREVIEW*/
  const dispatch = useDispatch();

  const ODOMETER_READING_REGEX = /^\d+$/;

  const internetChangeListener = useMemo(async () => {
    console.log(
      "*** RCBPreviewScreen  useMemo internetAvailable ",
      internetAvailable
    );
    console.log("in Memo internetAvailable", internetAvailable);
    if (internetAvailable) {
      console.log(
        "*** RCBPreviewScreen  useMemo  inside internetAvailable ",
        internetAvailable
      );
      try {
        var vechicleData = await Database.get("PIVechicleData");
        if (
          vechicleData?.activityId == 0 ||
          vechicleData?.activityId == undefined ||
          vechicleData?.activityId == null
        ) {
          setIsLoading(true);
          CreateActivityId(
            async () => {
              const vechicleData = await Database.get("PIVechicleData");
              var registrationNumber = vechicleData?.licensePlateNumber;
              var quoteNumber = vechicleData?.quoteNumber;
              var activityTypeId = vechicleData?.activityTypeId;
              var activityId = vechicleData?.activityId;
              var toTutorial = vechicleData?.toTutorial;
              var toWithQuote = vechicleData?.toWithQuote;

              dispatch({
                type: "ACTIVITY_DATA",
                payload: {
                  activityId: activityId,
                  activityTypeId: activityTypeId,
                  licensePlateNumber:
                    registrationNumber === undefined ? "" : registrationNumber,
                  toWithQuote: toWithQuote,
                  toTutorial: toTutorial,
                  quoteNumber: quoteNumber,
                },
              });
              setIsLoading(false);
            },
            (sensorImageDetails) => {
              dispatch({
                type: "SENSOR_DETAILS",
                payload: sensorImageDetails,
              });
              setIsLoading(false);
            }
          );
        } else {
          setIsLoading(false);
        }
      } catch (error) {
        console.log("Error in RCBPreviewScreen.js CreateActivityId()", error);
        setIsLoading(false);
      }
    }
  }, [internetAvailable]);

  useEffect(() => {
    getOdoInstruction();
    let Immersive = undefined;
    let restoreImmersive = undefined;
    if (!iOS) {
      Immersive = require("react-native-immersive").Immersive;
      Immersive.setImmersive(true);
      restoreImmersive = () => {
        __DEV__ && console.log("Immersive state changed!");
        Immersive.setImmersive(true);
      };
      Immersive.addImmersiveListener(restoreImmersive);
    }
    Orientation.lockToPortrait();

    let unsubscribe = navigation.addListener("focus", () => {
      Orientation.lockToPortrait();
      getOdoInstruction();
    });
    // disabled back handler
    const backHandler = BackHandler.addEventListener(
      "hardwareBackPress",
      () => {
        return true;
      }
    );

    const unsubscribeNetInfo = NetInfo.addEventListener(async (state) => {
      console.log(
        "*** RCBPreviewScreen  useMemo internetAvailable state ",
        state
      );
      if (state) {
        setInternetAvailable(state.isInternetReachable);
      }
    });

    return () => {
      if (Immersive !== undefined) {
        Immersive.off();
        Immersive.removeImmersiveListener(restoreImmersive);
      }

      backHandler.remove();
      unsubscribe();
      unsubscribeNetInfo && unsubscribeNetInfo();
    };
  }, []);

  const savaDataToRealm = async (value) => {
    UELogEvent("Odometer. saveDataToRealm, PIOdometerData", {
      readings: JSON.stringify(value),
    });
    console.log("**** saveDataToRealm before Odometer: " + value);
    await Database.update("PIOdometerData", {
      readings: value,
    });
    const odo = await Database.get("PIOdometerData");
  };

  const getOdoInstruction = async () => {
    var instructionInDb = await Database.get("PIVechicleInstruction");
    const item = JSON.parse(instructionInDb?.instuction).find(
      (item) => item.imageName === "DBD"
    );
    if (item !== undefined) {
      setOdometerInstructionData(item);
      forceUpdate();
    }
  };


  // If odometer reading is incorrect show error
  const renderError = () => {
    if (!odometerReadings.match(ODOMETER_READING_REGEX)) {
      return <Text style={[style.errorText]}>Invalid Odometer Reading</Text>;
    }
    return null;
  }

  return (
    <KeyboardAvoidingView
      style={{ flex: 1, backgroundColor: Colors.white }}
      behavior={iOS ? "padding" : ""}
      enabled
    >
      <ScrollView contentContainerStyle={{ flexGrow: 1, padding: 24 }}>
        <View>
          <Text style={styles.HeaderText}>{"Your’e Awesome!"}</Text>
          <Text style={styles.subHeaderText}>
            {"One last step before submitting"}
          </Text>
          <Text style={styles.titleText}>
            {OdometerInstructionData?.stepTitle}
          </Text>
        </View>

        <Image
          source={{ uri: OdometerInstructionData?.stepAssests }}
          style={{
            alignSelf: "center",
            marginTop: 12,
            aspectRatio: 3 / 2,
            width: "99%",
          }}
          onError={() => {
            console.log("***Odometer.js, Image Load Error");
          }}
        />

        <View style={styles.infoMainView}>
          {/* i Icon view */}
          <View style={styles.infoIconView}>
            <Ibutton />
          </View>
          {/* info view */}
          <View style={styles.infoMainTextView}>
            <Text style={styles.TextView}>
              <Text style={styles.boldText}>{"Note: "}</Text>
              <Text style={styles.normalText}>
                {" Odometer reading indicates the "}
              </Text>
              <Text style={styles.boldText}>
                {"total distance the vehicle has travelled! "}
              </Text>
              <Text style={styles.normalText}>
                {
                  "Please ensure the reading reflects that and is not set to display trip reading."
                }
              </Text>
            </Text>
          </View>
        </View>

        <View style={{ justifyContent: "center" }}>
          <View style={{ marginTop: 18 }}>
            <TextInput
              returnKeyType="done"
              keyboardType={"number-pad"}
              label={"Enter Odometer Reading (in Km)"}
              value={"" + odometerReadings}
              onChangeText={(value) => {
                setOdometerReadings(value);
              }}
              errorMsge={""}
            />
            <Text
              style={{
                position: "absolute",
                right: 10,
                top: "40%",
                fontSize: 16,
                fontFamily: "Muli-Regular",
                color: "#999999",
              }}
            >
              Km
            </Text>

          </View>
          {renderError()}

          <PrimaryButton
            style={{ marginVertical: 16 }}
            onPress={() => {
              if (
                odometerReadings === undefined ||
                odometerReadings.length <= 0
              ) {
                Alert.alert("Enter valid readings");
                return;
              } else {
                savaDataToRealm(odometerReadings);
                navigation.navigate("VideoPIProgress");
              }
            }}
            disabled={!odometerReadings.match(ODOMETER_READING_REGEX)}
          >
            {"Submit"}
          </PrimaryButton>
        </View>
      </ScrollView>
    </KeyboardAvoidingView>
  );
};
export default Odometer;

const styles = StyleSheet.create({
  safeArea: {
    flex: 1,
    backgroundColor: "white",
  },
  main: {
    flex: 1,
    margin: 24,
  },
  HeaderText: {
    fontSize: 22,
    fontFamily: "Muli-ExtraBold",
  },
  subHeaderText: {
    fontFamily: "Muli-Regular",
    fontSize: 16,
    color: "#444444",
  },
  titleText: {
    fontSize: 16,
    fontFamily: "Muli-Regular",
    color: "#000000",
    marginTop: 20,
  },
  infoMainView: {
    backgroundColor: "#FFFAEB",
    flexDirection: "row",
    marginVertical: 8,
    paddingVertical: 8,
  },
  infoIconView: {
    paddingHorizontal: 16,
    flex: 0.05,
    justifyContent: "flex-start",
  },
  infoMainTextView: {
    flex: 0.95,
    flexDirection: "row",
  },
  TextView: {
    // marginVertical: 8,
    // alignItems: "center",
  },
  boldText: {
    fontFamily: "Muli-ExtraBold",
    fontSize: 13,
  },
  normalText: {
    fontFamily: "Muli-Regular",
    fontSize: 13,
  },
});
