import React, { useEffect, useState } from "react";
import {
  StyleSheet,
  View,
  Image,
  Text,
  BackHandler,
  Alert,
} from "react-native";
import { translate } from "react-native-digitcamera/src/common/localize/i18n";
import { ProgressBar } from "react-native-paper";
import reactotron from "reactotron-react-native";
import Header from "./Header";
import Orientation from "../../../react-native-orientation";
import { useSelector } from "react-redux";
import {
  UELogEvent,
  UELogMessage,
} from "../common/libEventLog/UserExperior/LibUserExperior";
import Database from "../../../../Components/common/DAsyncStorage";
import { PrimaryButton } from "../../../../Components/common/ThemedComponents";
var totalImages = 0;
var docProgress = 0;
var uploadedInterval;
const VideoPIProgress = ({ navigation, route }) => {
  const [, updateState] = React.useState();
  const forceUpdate = React.useCallback(() => updateState({}), []);
  const [isUploadFailed, setIsUploadFailed] = useState(false);
  const [progress, setProgress] = useState(0);
  useEffect(() => {
    Orientation.lockToPortrait();
    const getUploadedData = async () => {
      var PIVideoCompleteStatus = await Database.get("PIVideoCompleteStatus");
      var completedCount = PIVideoCompleteStatus?.completePercentage;
      if (
        completedCount == undefined ||
        completedCount == "NaN" ||
        completedCount == null
      ) {
        completedCount = 0;
      }
      console.log(
        "*** VideoPIProgress getUploadedDaata completedCount: " + completedCount
      );
      setProgress(completedCount);
      docProgress = completedCount;
      // UELogEvent("VideoPIProgress. useEffect, completedCount, ", {
      //   "completedCount": JSON.stringify(completedCount)
      // })
      const mediaStatusObjs = await Database.get("PIMediaStatus");
      // UELogEvent("VideoPIProgress.  useEffect, mediaStatusObj, ", {
      //   "mediaStatusObj": JSON.stringify(mediaStatusObjs)
      // })
      totalImages = mediaStatusObjs?.length;
      // UELogEvent("VideoPIProgress.  useEffect, totalImage, ", {
      //   "totalImages": JSON.stringify(totalImages)
      // })
      var uploadedImages = [];
      var failedUploads = [];

      mediaStatusObjs.map((item, index) => {
        if (item?.status === "uploaded") {
          uploadedImages.push(item);
        }
        if (item?.status === "failed") {
          failedUploads.push(item);
        }
      });

      console.log(
        "**** Progress totalImages: " +
          totalImages +
          " -> uploadedImages: " +
          uploadedImages?.length +
          "  : failedUploads: " +
          failedUploads?.length
      );
      if (failedUploads?.length + uploadedImages?.length == totalImages) {
        if (failedUploads?.length > 0) {
          clearInterval(uploadedInterval);
          setIsUploadFailed(true);
          navigateTOthankYou(true);
        } else {
          clearInterval(uploadedInterval);
          navigateTOthankYou(false);
        }
      }

      // UELogEvent("VideoPIProgress.  useEffect, uploadedImages length ", {
      //   "uploadedImages": JSON.stringify(uploadedImages.length)
      // })
      console.log("**** Progress uploadedImages: " + uploadedImages.length);
    };
    uploadedInterval = setInterval(() => {
      getUploadedData();
    }, 1000);

    let unsubscribe = navigation.addListener("focus", () => {
      Orientation.lockToPortrait();
    });

    const backHandler = BackHandler.addEventListener(
      "hardwareBackPress",
      () => {
        return true;
      }
    );

    return () => {
      backHandler.remove();
      unsubscribe();
      if (uploadedInterval) {
        clearInterval(uploadedInterval);
      }
    };
  }, []);

  const navigateTOthankYou = async (isUploadFailed) => {
    /*
     * Checking if any one of the upload fails
     * If fails redirecting user to Withquote.js
     *
     */
    var AppLoginStatus = await Database.get("AppLoginStatus");
    if (isUploadFailed) {
      clearInterval(uploadedInterval);
      // clearInterval(uploadedInterval)
      Alert.alert("Oops!", "Something went wrong, please retry again", [
        {
          text: "OK",
          onPress: () => {
            // delete mediastatus data from realm
            try {
              console.log(
                "($)=> VideoPIProgress.js Deleting PIMediaStatus from realm"
              );
              Database.remove("PIMediaStatus");
            } catch (e) {
              console.log(
                "(&)=> VideoPIProgress.js, Error in deleting PIMediaStatus from realms =>",
                e
              );
            }
            if (AppLoginStatus?.userType === "OEMDealer") {
              route.params.props.navigation.navigate("VehicleInspection");
            } else {
              navigation.navigate("WithQuote");
            }
          },
        },
      ]);
    }

    console.log("*** VideoPIProgress.js docProgress: " + docProgress);
    if (docProgress >= 100) {
      clearInterval(uploadedInterval);
      var PIVechicleData = await Database.get("PIVechicleData");
      var activityId = PIVechicleData?.activityId;
      navigation.navigate("ThankYou", { activityId: activityId });
    }
  };

  return (
    <View style={styles.main}>
      <Header
        hideArrowBackButton={true}
        onlanguagechange={() => {
          forceUpdate();
        }}
        onbackPress={() => {
          navigation.goBack();
        }}
      />
      {/* GIF view */}
      <View style={styles.gifView}>
        <Image
          source={{
            uri: "https://d2h44aw7l5xdvz.cloudfront.net/assets/gif/cycle.gif",
          }}
          style={{
            width: "50%",
            height: "50%",
            alignSelf: "center",
            resizeMode: "center",
          }}
        />
      </View>
      {/* Progress View */}
      <View style={styles.progressView}>
        <Text style={styles.boldText}>{"Uploading in progress"}</Text>
        <ProgressBar
          progress={docProgress * 0.01}
          color={"#FFBB00"}
          style={{ height: 12, borderRadius: 6, backgroundColor: "#F5F5F5" }}
        />
        <Text style={styles.doneText}>
          {Math.floor(docProgress) + "% Done"}
        </Text>
        <Text style={styles.subText}>
          {
            "Once the upload is done, we will let you know. You can continue using your phone till then."
          }
        </Text>
      </View>
      <View style={styles.buttonView}>
        {/* <PrimaryButton
          onPress={() => {
            console.log("on Goto Homescreen >>> ");
          }}
          style={{ margin: 24 }}
        >
          {"Go to Homescreen"}
        </PrimaryButton> */}
      </View>
    </View>
  );
};
const styles = StyleSheet.create({
  main: {
    flex: 1,
    backgroundColor: "#FFFFFF",
  },
  gifView: {
    flex: 0.5,
    justifyContent: "center",
    marginBottom: 40,
    marginLeft: 24,
    marginRight: 24,
    alignItems: "center",
  },
  progressView: {
    flex: 0.4,
    marginLeft: 24,
    marginRight: 24,
  },
  processingText: {
    fontFamily: "Muli-Bold",
    fontSize: 20,
    alignSelf: "center",
    marginBottom: 15,
  },
  boldText: {
    fontFamily: "Muli-Regular",
    fontSize: 20,
    alignSelf: "center",
    marginBottom: 24,
  },
  doneText: {
    fontFamily: "Muli-Regular",
    fontSize: 14,
    marginTop: 12,
    alignSelf: "center",
  },
  subText: {
    fontFamily: "Muli-ExtraBold",
    fontSize: 14,
    marginTop: 16,
    alignSelf: "center",
  },
  buttonView: {
    flex: 0.1,
    justifyContent: "center",
  },
});
export default VideoPIProgress;
