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, useSelector } from "react-redux";
import {
  Ibutton,
  Spinner,
} from "react-native-digitcamera/src/common/ThemedComponents";
import {
  ODOMETER_READING_REGEX,
  SCREEN_HEIGHT,
} from "../../../../Components/common/Constants";
import {
  // PrimaryButton,
  TextInput,
} from "../../../../Components/common/ThemedComponents";
import { PrimaryButton } from "../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";
import { useIsFocused } from "@react-navigation/native";
import {
  getCurrentActivity,
  updateActivityStatus,
} from "react-native-digitcamera/src/Screens/OfflineFlow/CommonFunc";

var isFocused;

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

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

  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.lockToLandscapeLeft();

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

    return () => {
      if (Immersive !== undefined) {
        Immersive.off();
        Immersive.removeImmersiveListener(restoreImmersive);
      }
      backHandler.remove();
    };
  }, []);

  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) ||
      odometerReadings.length == 0
    ) {
      return <Text style={[style.errorText]}>Invalid Odometer Reading</Text>;
    }
    return null;
  };

  const handleContinue = async () => {
    if (odometerReadings === undefined || odometerReadings.length <= 0) {
      Alert.alert("Enter valid readings");
      return;
    } else {
      var activity = await getCurrentActivity();
      console.log(
        "Odometer : getCurrentActivity ",
        JSON.stringify(activity, null, "  ")
      );
      await updateActivityStatus("IN-PROGRESS", activity);
      await savaDataToRealm(odometerReadings);
      navigation.navigate("ActivityScreen");
    }
  };

  return (
    <KeyboardAvoidingView
      style={{ flex: 1, backgroundColor: Colors.white }}
      behavior={"padding"}
      enabled
    >
      <View style={{ flex: 1 }}>
        <View style={styles.main}>
          <Text style={styles.HeaderText}>{"Your’e Awesome!"}</Text>
          <Text style={styles.subHeaderText}>
            {"One last step before submitting"}
          </Text>

          <View style={styles.subView}>
            {/* Image View */}
            <View style={styles.imageView}>
              <Image
                source={{
                  uri: OdometerInstructionData?.stepAssests,
                  cache: "only-if-cached",
                }}
                style={{
                  alignSelf: "center",
                  marginTop: 12,
                  aspectRatio: 3 / 2,
                  width: "99%",
                }}
                onError={() => {
                  console.log("***Odometer.js, Image Load Error");
                }}
              />
            </View>
            {/* Blank View */}
            <View style={styles.blankView} />
            {/* Instuction view */}
            <View style={{ flex: 0.5 }}>
              {/* lable View */}
              <View style={{ flex: 0.5 }}>
                <Text style={styles.titleText}>
                  {OdometerInstructionData?.stepTitle}
                </Text>
                <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>
              {/* Input View */}

              <View style={{ justifyContent: "center", flex: 0.5 }}>
                <View style={{ marginTop: 18 }}>
                  <TextInput
                    returnKeyType="done"
                    keyboardType={"phone-pad"}
                    label={"Odometer Reading"}
                    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()}
              </View>
            </View>
          </View>
        </View>
        <View style={styles.goToHomeScreenView}>
          <PrimaryButton
            onPress={handleContinue}
            disabled={!odometerReadings.match(ODOMETER_READING_REGEX)}
            style={{
              backgroundColor: Colors.digitYellow,
              alignSelf: "flex-end",
              marginRight: 26,
            }}
          >
            {"Continue"}
          </PrimaryButton>
        </View>
      </View>
    </KeyboardAvoidingView>
  );
};
export default Odometer;

const styles = StyleSheet.create({
  safeArea: {
    flex: 1,
    backgroundColor: "white",
  },
  main: {
    flex: 0.9,
    marginLeft: 24,
    marginRight: 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,
  },
  subView: {
    flex: 1,
    flexDirection: "row",
  },
  imageView: {
    flex: 0.4,
    justifyContent: "center",
  },
  blankView: {
    flex: 0.1,
  },
  goToHomeScreenView: {
    flex: 0.2,
    justifyContent: "center",
  },
});
