import React, { useEffect, useRef, useState } from "react";
const iOS = Platform.OS === "ios";
import {
  BackHandler,
  Image,
  Platform,
  StatusBar,
  StyleSheet,
  Text,
  View,
  Alert,
  ScrollView,
} 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";

const Odometer = ({ navigation, route }) => {
  const [odometerReadings, setOdometerReadings] = useState("");
  const [, updateState] = React.useState();
  const [OdometerInstructionData, setOdometerInstructionData] = useState();
  const forceUpdate = React.useCallback(() => updateState({}), []);
  /*@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.lockToPortrait();

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

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

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

  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");
    console.log("**** saveDataToRealm after Odometer: " + JSON.stringify(ado));
  };

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

  return (
    <SafeAreaView
      edges={iOS ? ["top", "bottom", "right"] : []}
      style={styles.safeArea}
    >
      <View style={styles.main}>
        <Spinner loading={false} />
        <StatusBar hidden={true} />
        <View style={{ flex: 0.9 }}>
          <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>
          <Image
            source={{ uri: OdometerInstructionData?.stepAssests }}
            height={"45%"}
            width={"99%"}
            style={{ alignSelf: "center", marginTop: 12 }}
            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>

          <TextInput
            returnKeyType="done"
            keyboardType={"number-pad"}
            style={{ marginHorizontal: 5, marginVertical: 18 }}
            label={"Enter Odometer Reading (in Km)"}
            value={"" + odometerReadings}
            onChangeText={(value) => {
              setOdometerReadings(value);
            }}
            errorMsge={""}
          />
        </View>

        <View style={{ flex: 0.1, justifyContent: "center" }}>
          <PrimaryButton
            style={{ marginVertical: 10 }}
            onPress={() => {
              if (
                odometerReadings === undefined ||
                odometerReadings.length <= 0
              ) {
                Alert.alert("Enter valid readings");
                return;
              } else {
                savaDataToRealm(odometerReadings);
                navigation.navigate("VideoPIProgress");
              }
            }}
          >
            {"Submit"}
          </PrimaryButton>
        </View>
      </View>
    </SafeAreaView>
  );
};
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",
    marginTop: 4,
  },
  infoIconView: {
    padding: 15,
    flex: 0.05,
    justifyContent: "center",
  },
  infoMainTextView: {
    flex: 0.95,
    flexDirection: "row",
    justifyContent: "center",
  },
  TextView: {
    marginVertical: 8,
    alignItems: "center",
  },
  boldText: {
    fontFamily: "Muli-ExtraBold",
    fontSize: 13,
  },
  normalText: {
    fontFamily: "Muli-Regular",
    fontSize: 13,
  },
});
