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 { useDispatch, useSelector } from "react-redux";
import {
  UELogEvent,
  UELogMessage,
} from "../common/libEventLog/UserExperior/LibUserExperior";
import Database from "../../../../Components/common/DAsyncStorage";
import {
  offlinePIDataToRealm,
  updateActivityStatus,
} from "react-native-digitcamera/src/Screens/OfflineFlow/CommonFunc";
import NetInfo from "@react-native-community/netinfo";
import Modal from "../common/Modal";
import { PrimaryButton } from "../../../../Components/common/ThemedComponents";
import { CreateActivityId } from "react-native-digitcamera/src/Screens/OfflineFlow/CreateActivityId";
import Colors from "../../../../Components/common/Colors";
import { startOfflineBackgroundUpload } from "react-native-digitcamera/src/Screens/SilentUpload/SilentUploadUtils";
import { NamedModal } from "react-native-digitcamera/src/common/GlobalModal";
const isAndroid = Platform.OS === "android" ? true : false;

/* 
[IMPORTANT]
directly importing redux store as store
gives access to disptach/getState methods

using useSelector to access state results in redux having the latest data,
but the component is not in sync with redux.
to be synced with component, it needs to re-render.

I am using store.getState().reducer.state inside the interval to get the latest data and be in sync with
without updating the state of the component
*/
import store from "react-native-digitcamera/src/redux/store";

let totalImages = 0;
let uploadedInterval = [];
let uploadedImages = [];
let retryCount = 1;
let failedUploads = [];

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

  const { TotalImage } = route.params;
  const dispatch = useDispatch();

  const network = useSelector((state) => state.network);
  const { isInternetReachable } = network;

  useEffect(() => {
    dispatch({
      type: "ENABLE_CREATE_ACTIVITY",
    });
    if (isInternetReachable === true) {
      setIsInternetConnected(true);
      dispatch({
        type: "GLOBAL_MODAL_HIDE",
      });
    } else if (isInternetReachable === false) {
      clearInterval(uploadedInterval);
      dispatch({
        type: "GLOBAL_MODAL_SHOW",
        payload: NamedModal.NO_INTERNET_ACCESS_UPLOADING,
      });
      setIsInternetConnected(false);
      // Clear failed data
      dispatch({
        type: "CLEAR_FAILED_DATA",
      });
    }
  }, [network]);

  const setPIOnProgress = async () => {
    // should calll only oncece when we land on this screen
    await updateActivityStatus("IN-PROGRESS");
    await Database.set("PIOnProgress", "true");
    await Database.set("PIOnProgressScreen", "true");
    await offlinePIDataToRealm(true);
  };

  useEffect(() => {
    setPIOnProgress();
    showActivity();
    uploadedImages = [];

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

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

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

  const getUploadedData = async () => {
    try {
      const mediaStatusObjs = await Database.get("PIMediaStatus");
      var PIVechicleData = await Database.get("PIVechicleData");
      var activityId = PIVechicleData?.activityId;
      showFailedError();
      console.log(" progress.js mediaStatusObjs", mediaStatusObjs);
      console.log(" progress.js PIVechicleData", PIVechicleData);

      var currentActivity = mediaStatusObjs.filter((activity) => {
        return activity.activityId == activityId;
      });
      var currentActivityImages = currentActivity[0]?.mediaUpload;
      console.log(
        "[Info] . Progress . useEffect . currentActivityImages - HH",
        JSON.stringify(currentActivity, null, "  "),
        currentActivityImages
      );

      totalImages = currentActivityImages?.length;

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

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

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

      uploadedImages = currentActivityImages?.filter(
        (item) => item?.status === "uploaded"
      );
      if (
        uploadedImages.length !== undefined ||
        uploadedImages.length !== null
      ) {
        setUploadedCount(uploadedImages.length);
      }
      failedUploads =
        currentActivityImages.filter((item) => item?.status === "failed") ?? [];

      console.log(
        "[INFO] . Progress . failedUploads - ",
        JSON.stringify(failedUploads, null, " ")
      );

      console.log(
        "**** Progress totalImages: " +
          totalImages +
          " -> uploadedImages: " +
          uploadedImages?.length +
          "  : failedUploads: " +
          failedUploads?.length
      );

      if (failedUploads?.length + uploadedImages?.length === totalImages) {
        if (uploadedImages?.length === totalImages) {
          navigateTOthankYou();
        }
      }

      console.log("**** Progress uploadedImages: " + uploadedImages.length);
    } catch (error) {
      console.log("Progress.js Error getUploadedData() : ", error);
    }
  };

  const showFailedError = async () => {
    const isReUploadFailed = await Database.get("PIReUploadFailed");
    console.log(
      "[INFO] . Progress . showFailedError . isReUploadFailed - ",
      isReUploadFailed
    );
    if (isReUploadFailed) {
      clearInterval(uploadedInterval);
      setUploadedCount(0);
      if (isInternetConnected) {
        dispatch({
          type: "GLOBAL_MODAL_SHOW",
          payload: NamedModal.DOCUMENT_UPLOAD_ERROR,
        });
      }
    }
  };

  const navigateTOthankYou = async () => {
    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");
    if (!canGoHomeScreen) {
      navigation.navigate("ThankYou", {
        activityId: activityId,
      });
    }
  };

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

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

  const handleGoToHome = async () => {
    await showActivity();
    Orientation.lockToPortrait();
    clearInterval(uploadedInterval);
    navigation.navigate("WithQuote");
  };
  const showActivity = async () => {
    setCanGoHomeScreen(true);
    await Database.update("PICanShowActivity", {
      isShowActivityScreen: true,
    });
  };
  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>
        <PrimaryButton onPress={handleGoToHome} style={{ marginTop: 20 }}>
          Go To Home
        </PrimaryButton>
      </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;
