import React, { useEffect, useMemo, 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 { offlinePIDataToRealm } from "react-native-digitcamera/src/Screens/OfflineFlow/CommonFunc";
import NetInfo from "@react-native-community/netinfo";

var totalImages = 0;
var uploadedInterval = [];
var uploadedImages = [];

const Progress = ({ navigation, route }) => {
  const [isUploadFailed, setIsUploadFailed] = useState(false);
  const [uploadedCount, setUploadedCount] = useState(0)
  const [totalCount, setTotalCount] = useState(0)
  const [isInternetConnected, setIsInternetConnected] = useState(true);

  const { TotalImage } = route.params;
  const internetChangeListener = useMemo(async () => {
    var AppLoginStatus = await Database.get("AppLoginStatus");
    Orientation.lockToPortrait();
    if (!isInternetConnected) {
      uploadFailedAlert(AppLoginStatus)
    }
  }, [isInternetConnected]);
  useEffect(() => {
    uploadedImages = [];
    Orientation.lockToPortrait();

    const getUploadedData = async () => {
      const mediaStatusObjs = await Database.get("PIMediaStatus");

      console.log("[Info] . Progress . useEffect . mediaStatusObjs - ", mediaStatusObjs);

      totalImages = TotalImage;

      console.log("[Info] . Progress . useEffect . mediaStatusObjs.length - ", totalImages);

      // UELogEvent("VideoPIProgress.  useEffect, totalImage, ", {
      //   "totalImages": JSON.stringify(totalImages)
      // })

      if (totalImages !== undefined || totalImages !== null) {
        setTotalCount(totalImages)
      }

      var failedUploads = [];

      setTimeout(() => {
        uploadedImages = mediaStatusObjs?.filter(item => item?.status === "uploaded");
        if (uploadedImages.length !== undefined || uploadedImages.length !== null) {
          setUploadedCount(uploadedImages.length)
        }
        failedUploads = mediaStatusObjs?.filter(item => item?.status === "failed");
      }, 3000)


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

      console.log("**** Progress uploadedImages: " + uploadedImages.length);
    };

    uploadedInterval = setInterval(() => {
      console.log("[Info] . Progress . uploadedInterval is running ")
      getUploadedData();
    }, 1000);

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

    var unsubscribeNetInfo = NetInfo.addEventListener(async (state) => {
      console.log("In NetInfo progress.js");
      if (state.isInternetReachable) {
        setIsInternetConnected(true);
      } else {
        setIsInternetConnected(false);
      }
    });
    const backHandler = BackHandler.addEventListener(
      "hardwareBackPress",
      () => {
        return true;
      }
    );

    return () => {
      backHandler.remove();
      unsubscribeNetInfo && unsubscribeNetInfo()
      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 (false) {
      clearInterval(uploadedInterval);
      // clearInterval(uploadedInterval)
      Alert.alert("Oops!", "Something went wrong, please retry again", [
        {
          text: "OK",
          onPress: async () => {
            // delete mediastatus data from realm
            try {
              console.log(
                "($)=> VideoPIProgress.js Deleting PIMediaStatus from realm"
              );
              await Database.remove("PIMediaStatus");
              clearInterval(uploadedInterval);
            } 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");
            }
          },
        },
      ]);
    }
    clearInterval(uploadedInterval);
    var PIVechicleData = await Database.get("PIVechicleData");
    var activityId = PIVechicleData?.activityId;
    // docProgress = 0;
    totalImages = 0;
    // experiment
    // uploadedImages = [];
    await Database.remove("PIMediaStatus");
    await Database.remove("PIOfflineVechicleData");
    navigation.replace("ThankYou", { activityId: activityId });
  };

  const uploadFailedAlert = (AppLoginStatus) => {
    Alert.alert("You are offline!", "We will try to upload images ones we get good internet", [
      {
        text: "OK",
        onPress: () => {
          // delete mediastatus data from realm
          try {
            console.log("called if no internet >>>>>>>>        >>>>>>>>>>>>         >>>>>>>>>");
            offlinePIDataToRealm(true)
          }
          catch (e) {
            console.log("(&)=> progress.js, Error in deleting PIMediaStatus from realms =>", e);
          }
          if (AppLoginStatus[0]?.userType === "OEMDealer") {
            route.params.props.navigation.navigate("VehicleInspection");
          }
          else {
            navigation.navigate("WithQuote");
          }
        }
      }
    ])
  }

  const getUploadPercentage = () => {

    if (uploadedCount === undefined || totalCount === undefined || uploadedCount === null || totalCount === null) {
      return 0;
    }

    if (uploadedCount === 0 || totalCount === 0) {
      return 0;
    }
    return (uploadedCount / totalCount)
  }




  return (
    <View style={styles.main}>
      <Header
        customTitle=""
        hideArrowBackButton={true}
        onbackPress={() => {
          navigation.goBack();
        }}
        shiftTitleToLeft={true}
      />
      {/* GIF view */}
      <View style={styles.gifView}>
        <Image
          source={{
            uri: "https://d2h44aw7l5xdvz.cloudfront.net/assets/gif/cycle.gif",
            cache: 'only-if-cached'
          }}
          style={{
            width: "100%",
            resizeMode: "contain",
            aspectRatio: 1
          }}
        />
      </View>
      {/* Progress View */}
      <View style={styles.progressView}>
        <Text style={styles.boldText}>{`Uploading Images ${uploadedImages.length} / ${totalImages}`}</Text >
        <ProgressBar
          progress={getUploadPercentage()}
          color={"#FFBB00"}
          style={{ height: 12, borderRadius: 6, backgroundColor: "#F5F5F5" }}
        />
        <Text style={styles.subText}>
          {
            "Please wait while the upload completes"
          }
        </Text>
      </View >

    </View >
  );
};
const styles = StyleSheet.create({
  main: {
    flex: 1,
    backgroundColor: "#FFFFFF",
  },
  gifView: {
    flex: 0.4,
    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-ExtraBold",
    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",
  },
  iconContainer: {
    flexDirection: "row",
    justifyContent: 'center',
    alignItems: "center"
  },
  iconLabel:
  {
    fontSize: 12,
    fontFamily: "Muli-Regular"
  }

});

export default Progress;