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

import { async } from "validate.js";
import { ActivityIndicator } from "react-native-paper";
const camera = require("../common/Image/camera.png");

var isFocused;

export const navigateToCamera = async (navigation, dispatch) => {
  dispatch({
    type: "SET_CURRENT_IMAGE",
    payload: "DBD",
  });

  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;
  navigation.navigate("Camera", {
    activityId,
    activityTypeId: 5,
    licensePlateNumber,
    toVDO: false,
    instruction: instuction,
    mlHardwareAvailable: false,
  });
};

function debounce(func, timeout = 3000) {
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => {
      func.apply(this, args);
    }, timeout);
  };
}

const saveOdometerReadings = async (odometer, trip) => {
  try {
    UELogEvent("Odometer Readings", {
      odometer: `${odometer}`,
      trip: `${trip}`,
    });
    await Database.set("PIOdometerData", {
      odometer: odometer,
      trip: trip,
    });
  } catch (e) {
    console.log("Error in PIOdometerData ", e);
  }
};

const Odometer = ({ navigation, route }) => {
  const [odometerReadings, setOdometerReadings] = useState("");
  const [tripReadings, setTripReading] = useState("");
  const [, updateState] = React.useState();
  const [OdometerInstructionData, setOdometerInstructionData] = useState();
  const forceUpdate = React.useCallback(() => updateState({}), []);
  const [validReadings, setValidReading] = useState(false);
  const [imageCaptured, setImageCaptured] = useState(false);
  const [imageSource, setImageSource] = useState("NOT_AVAILABLE");

  isFocused = useIsFocused();

  //will change this later
  //need to build one more odometer reducer to handle all the odometer data
  const OdometerUri = useSelector(
    (state) => state.rcbPreviewData.rcbPreviewData
  );

  useEffect(() => {
    if (OdometerUri.length !== 0) {
      const odometerExist = OdometerUri.find((item) => item.name === "DBD");
      if (odometerExist) {
        setImageSource(odometerExist.image);
        setImageCaptured(true);
        setValidReading(true);
      }
    }
  }, [OdometerUri]);

  /*
   on initial mount, fetch readings from database 
   if readings exist in database show it to the user
   otherwise dont.

   PIOdometerReadings should be clear on each new activity 
   and end of the activity.
   
   or once submit is pressed

   PIOdometerReadings should persist only during the navigation from odometer to camera & camera to odometer
   otherwise this database should be removed. 
  */
  useEffect(() => {
    const getExistingReadings = async () => {
      const PIOdometerData = await Database.get("PIOdometerData");
      if (PIOdometerData) {
        const { odometer, trip } = PIOdometerData;
        if (odometer && trip) {
          setOdometerReadings(odometer);
          setTripReading(trip);
          setValidReading(true);
        }
      }
    };
    getExistingReadings();
  }, []);

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

  const handleContinue = async () => {
    if (!odometerReadings.match(ODOMETER_READING_REGEX)) {
      Alert.alert("Alert", "Please enter valid odometer / trip readings");
      return;
    }

    if (tripReadings.length > 0) {
      if (!tripReadings.match(ODOMETER_READING_REGEX)) {
        Alert.alert("Alert", "Please enter valid odometer / trip readings");
        return;
      }
      if (parseFloat(tripReadings) > parseFloat(odometerReadings)) {
        Alert.alert(
          "Alert",
          "Trip Reading cannot be greater than Odometer reading"
        );
        return;
      }
    }

    var activity = await getCurrentActivity();
    console.log(
      "Odometer : getCurrentActivity ",
      JSON.stringify(activity, null, "  ")
    );
    await updateActivityStatus("IN-PROGRESS", activity);
    await saveOdometerReadings(odometerReadings, tripReadings);
    navigation.navigate("ActivityScreen");
  };

  return (
    <KeyboardAvoidingView
      style={{ flex: 1, backgroundColor: Colors.white }}
      behavior={iOS ? "padding" : ""}
      enabled
    >
      <View style={{ flex: 1 }}>
        <View style={styles.main}>
          <Text style={styles.HeaderText}>{"You're Awesome!"}</Text>
          <Text style={styles.subHeaderText}>
            {"Please provide odometer photo and odometer reading"}
          </Text>

          <View style={styles.subView}>
            {/* Image View */}
            <View style={styles.imageView}>
              <Image
                source={{
                  uri:
                    imageSource === "NOT_AVAILABLE"
                      ? OdometerInstructionData?.stepAssests
                      : imageSource,
                  cache: "only-if-cached",
                }}
                style={{
                  alignSelf: "center",
                  marginTop: 12,
                  aspectRatio: 3 / 2,
                  width: "99%",
                }}
                onError={() => {
                  console.log("***Odometer.js, Image Load Error");
                }}
              />
            </View>

            {/* Instuction view */}
            <View style={{ flex: 0.5 }}>
              {/* lable View */}
              <View
                style={{
                  flex: 0.4,

                  justifyContent: "flex-start",
                }}
              >
                <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: "space-between",
                  flex: 0.5,
                }}
              >
                <View
                  style={{
                    flexDirection: "row",
                    justifyContent: "space-between",
                  }}
                >
                  <View style={{ flex: 0.48, marginVertical: 16 }}>
                    <View style={{}}>
                      <TextInput
                        returnKeyType="done"
                        keyboardType={"phone-pad"}
                        label={"Odometer Reading"}
                        value={"" + odometerReadings}
                        onChangeText={(value) => {
                          setOdometerReadings(value);
                        }}
                        maxLength={10}
                        errorMsge={""}
                      />
                      <Text
                        style={{
                          position: "absolute",
                          right: 10,
                          top: "40%",
                          fontSize: 16,
                          fontFamily: "Muli-Regular",
                          color: "#999999",
                        }}
                      >
                        Km
                      </Text>
                    </View>
                  </View>
                  <View style={{ flex: 0.48 }}>
                    <View style={{ marginVertical: 16 }}>
                      <TextInput
                        returnKeyType="done"
                        keyboardType={"phone-pad"}
                        label={"Trip Reading"}
                        value={"" + tripReadings}
                        onChangeText={(value) => {
                          setTripReading(value);
                        }}
                        maxLength={10}
                        errorMsge={""}
                      />
                      <Text
                        style={{
                          position: "absolute",
                          right: 10,
                          top: "40%",
                          fontSize: 16,
                          fontFamily: "Muli-Regular",
                          color: "#999999",
                        }}
                      >
                        Km
                      </Text>
                    </View>
                  </View>
                </View>
                <View style={{ marginVertical: 8 }}>
                  {!imageCaptured && (
                    <PrimaryButton
                      style={{
                        backgroundColor: "white",
                        borderStyle: "dashed",
                        borderWidth: 1,
                      }}
                      onPress={() => {
                        if (!odometerReadings.match(ODOMETER_READING_REGEX)) {
                          Alert.alert(
                            "Alert",
                            "Please enter valid odometer / trip readings"
                          );
                          return;
                        }

                        if (tripReadings.length > 0) {
                          if (!tripReadings.match(ODOMETER_READING_REGEX)) {
                            Alert.alert(
                              "Alert",
                              "Please enter valid odometer / trip readings"
                            );
                            return;
                          }
                        }
                        saveOdometerReadings(odometerReadings, tripReadings);
                        navigateToCamera(navigation, dispatch);
                      }}
                      icon={({ color, size }) => {
                        return (
                          <Image
                            source={camera}
                            style={{ width: 30, height: 30 }}
                          />
                        );
                      }}
                    >
                      {"Click to Capture odometer photo"}
                    </PrimaryButton>
                  )}
                </View>
              </View>
            </View>
          </View>
        </View>
        <View style={styles.goToHomeScreenView}>
          {validReadings && imageCaptured && (
            <PrimaryButton
              onPress={handleContinue}
              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",
    justifyContent: "space-between",
  },
  imageView: {
    flex: 0.4,
    justifyContent: "center",
  },
  blankView: {
    flex: 0.1,
  },
  goToHomeScreenView: {
    flex: 0.2,
    justifyContent: "center",
  },
});
