import React, { useEffect, useState } from "react";
import {
  StyleSheet,
  View,
  Image,
  Text,
  BackHandler,
  Alert,
  Platform,
} 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 { useIsAppForeground } from "../common/useIsForeground";

import NetInfo from "@react-native-community/netinfo";
import {
  offlinePIDataToRealm,
  updateActivityStatus,
} from "react-native-digitcamera/src/Screens/OfflineFlow/CommonFunc";
import MCIcon from "react-native-vector-icons/MaterialCommunityIcons";
import { useMemo } from "react";
import {
  PrimaryButton,
  Spinner,
} from "react-native-digitcamera/src/common/ThemedComponents";
import { CreateActivityId } from "react-native-digitcamera/src/Screens/OfflineFlow/CreateActivityId";
import Modal from "../common/Modal";
import { SCREEN_WIDTH } from "../../../../Components/common/Constants";
import Colors from "../../../../Components/common/Colors";
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";
import { NamedModal } from "react-native-digitcamera/src/common/GlobalModal";
import { startOfflineBackgroundUpload } from "react-native-digitcamera/src/Screens/SilentUpload/SilentUploadUtils";

var totalImages = 0;
var docProgress = 0;
let uploadedInterval;
let retryCount = 1;
let uploadedImages = [];
let failedUploads = [];
const VideoPIProgress = ({ navigation, route }) => {
  const [, updateState] = React.useState();
  const forceUpdate = React.useCallback(() => updateState({}), []);
  const [isUploadFailed, setIsUploadFailed] = useState(false);
  const [progress, setProgress] = useState("0");
  const [isInternetConnected, setIsInternetConnected] = useState(true);
  const [isLoading, setIsLoading] = useState(false);
  const [canGoHomeScreen, setCanGoHomeScreen] = useState(false);
  const [uploadTimeAndSpeed, setUploadTimeAndSpeed] = useState({
    uploadSpeed: 0,
    secondsRemaining: 0,
  });

  const dispatch = useDispatch();

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

  useEffect(() => {
    if (isInternetReachable === true) {
      dispatch({
        type: "GLOBAL_MODAL_HIDE",
      });
      setIsInternetConnected(true);
      setIsLoading(false);
    } else if (isInternetReachable === false) {
      setIsInternetConnected(false);
      // once it shown to user on progress screen
      // we can create activity id because user has completed the flow
      dispatch({
        type: "GLOBAL_MODAL_SHOW",
        payload: NamedModal.NO_INTERNET_ACCESS_UPLOADING,
      });
      dispatch({
        type: "CLEAR_FAILED_DATA",
      });
    }
  }, [network]);

  const setPIOnProgress = async () => {
    await updateActivityStatus("IN-PROGRESS");
    await Database.set("PIOnProgress", "true");
    await Database.set("PIOnProgressScreen", "true");
    await offlinePIDataToRealm(true);
  };

  useEffect(() => {
    Orientation.lockToLandscapeLeft();
    // should calll only oncece when we land on this screen
    setPIOnProgress();
    showActivity();
    uploadedImages = [];
    failedUploads = [];

    uploadedInterval = setInterval(() => {
      getUploadedData();
    }, 1000);

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

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

  const getUploadedData = async () => {
    var PIVideoCompleteStatus = await Database.get("PIVideoCompleteStatus");
    var completedCount = PIVideoCompleteStatus?.completePercentage;
    let uploadInfo = PIVideoCompleteStatus?.uploadInfo;
    if (!isInternetConnected) {
      uploadInfo = { uploadSpeed: 0, secondsRemaining: 0 };
    }
    // console.log("($) VideoPIProgress . uploadInfo - ", uploadInfo);

    setUploadTimeAndSpeed(uploadInfo);

    if (
      completedCount == undefined ||
      completedCount == "NaN" ||
      completedCount == null
    ) {
      completedCount = 0;
    }
    // console.log(
    //   "*** VideoPIProgress getUploadedDaata completedCount: " + completedCount
    // );
    setProgress(completedCount);
    docProgress = completedCount;

    showFailedError();

    const mediaStatusObjs = await Database.get("PIMediaStatus");
    var PIVechicleData = await Database.get("PIVechicleData");

    var currentActivityData = mediaStatusObjs?.filter((activity) => {
      return activity.activityId == PIVechicleData?.activityId;
    });
    var allDocuments = currentActivityData?.[0]?.mediaUpload;

    const failedUploadsObjs =
      allDocuments.filter((item) => item?.status === "failed") ?? [];

    await getStatus();

    if (
      failedUploads?.length + uploadedImages?.length === totalImages &&
      mediaStatusObjs.length != 0
    ) {
      if (uploadedImages?.length === totalImages) {
        navigateTOthankYou();
      }
    }

    // UELogEvent("VideoPIProgress.  useEffect, uploadedImages length ", {
    //   "uploadedImages": JSON.stringify(uploadedImages.length)
    // })
    console.log(
      "**** VideoPIProgress.js uploadedImages: " + uploadedImages.length
    );
  };

  const getStatus = async () => {
    // for multiActivity
    // here we are filter current activity with Activity present in DB

    const mediaStatusObjs = await Database.get("PIMediaStatus");
    var PIVechicleData = await Database.get("PIVechicleData");

    var currentActivityData = mediaStatusObjs?.filter((activity) => {
      return activity.activityId == PIVechicleData?.activityId;
    });
    var allDocuments = currentActivityData?.[0]?.mediaUpload;

    const failedUploadsObjs =
      allDocuments.filter((item) => item?.status === "failed") ?? [];

    console.log(
      "videoPIProgress currentActivityData : ",
      JSON.stringify(currentActivityData, null, "  ")
    );
    var allDocuments = currentActivityData?.[0]?.mediaUpload;
    totalImages = allDocuments?.length;
    uploadedImages = allDocuments?.filter(
      (item) => item?.status === "uploaded"
    );

    // gatting from redux insted of DB
    failedUploads = failedUploadsObjs;

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

  const showFailedError = async () => {
    const isReUploadFailed = await Database.get("PIReUploadFailed");
    // console.log(
    //   "[INFO] . VideoPIProgress . showFailedError . isReUploadFailed - ",
    //   isReUploadFailed
    // );
    if (isReUploadFailed) {
      clearInterval(uploadedInterval);
      // set progress bar to
      docProgress = 0;
      setProgress(0);
      if (isInternetConnected) {
        dispatch({
          type: "GLOBAL_MODAL_SHOW",
          payload: NamedModal.DOCUMENT_UPLOAD_ERROR,
        });
      }
    }
  };
  const showActivity = async () => {
    clearInterval(uploadedInterval);
    setCanGoHomeScreen(true);
    await Database.update("PICanShowActivity", {
      isShowActivityScreen: true,
    });
  };
  const navigateTOthankYou = async () => {
    clearInterval(uploadedInterval);
    /*
     * Checking if any one of the upload fails
     * If fails redirecting user to Withquote.js
     *
     */
    console.log("[INFO] . VideoPIProgress . navigateToThankYou ");

    console.log(
      "*** VideoPIProgress.js docProgress: " + docProgress,
      isInternetConnected
    );
    if (isInternetConnected) {
      console.log(
        "isInternetConnected ",
        isInternetConnected,
        docProgress >= 100
      );
      if (docProgress >= 100) {
        var PIVechicleData = await Database.get("PIVechicleData");
        console.log("Before");
        var activityId = PIVechicleData?.activityId;
        console.log("After");
        setProgress(0);
        totalImages = 0;
        // docProgress = 0;
        // totalImages = 0;

        if (!canGoHomeScreen) {
          navigation.navigate("ThankYou", {
            activityId: activityId,
          });
        }
      }
    }
  };

  const getEstimatedSeconds = (sec) => {
    if (sec === undefined || sec === null) {
      return 0;
    }
    return getTimeInMinAndSec(sec);
  };

  const getSpeedInMbps = (speed) => {
    if (speed === undefined || speed === null) {
      return `0 Mbps`;
    }
    return `${(speed / 1024).toFixed(3)} Mbps`;
  };

  const getTimeInMinAndSec = (sec) => {
    if (sec === undefined || sec === null) {
      return `0 sec`;
    }
    const min = sec / 60;
    const remSec = sec % 60;
    return `${Math.floor(min)} min ${Math.floor(remSec)} sec`;
  };

  const handleGoToHome = () => {
    if (isAndroid) {
      Alert.alert(
        "Exit app",
        "Stay relax, we will upload your documents even if you exit the app",
        [
          {
            text: "Cancel",
            onPress: () => null,
            style: "cancel",
          },
          { text: "YES", onPress: () => BackHandler.exitApp() },
        ]
      );
    }
  };

  return (
    <View style={styles.main}>
      <Spinner loading={isLoading} />
      <Header
        customTitle="Upload in progress"
        hideArrowBackButton={false}
        onlanguagechange={() => {
          forceUpdate();
        }}
        onbackPress={() => {
          navigation.goBack();
        }}
        shiftTitleToLeft={false}
      />
      <View style={styles.componentView}>
        {/* 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>
        {/* Blank View */}
        <View style={styles.blankView} />
        {/* Progress View */}
        <View style={styles.progressView}>
          <View style={styles.progressBarView}>
            <ProgressBar
              progress={docProgress * 0.01}
              color={"#FFBB00"}
              style={{
                height: 12,
                borderRadius: 6,
                backgroundColor: "#F5F5F5",
              }}
            />
            <View
              style={{
                flexDirection: "row",
                justifyContent: "space-between",
              }}
            >
              <View
                style={{
                  flex: 0.4,
                  justifyContent: "space-between",
                }}
              >
                <Text style={styles.doneText}>
                  <Text style={{ fontWeight: "800" }}>
                    {Math.floor(docProgress)}%
                  </Text>{" "}
                  Done
                </Text>
              </View>
              <View
                style={{
                  flex: 0.5,
                  alignSelf: "flex-end",
                }}
              >
                {isInternetConnected && (
                  <View
                    style={{
                      marginVertical: 10,
                      flexDirection: "row",
                      justifyContent: "space-between",
                    }}
                  >
                    {/* Spped view */}
                    <View style={styles.iconContainer}>
                      <MCIcon
                        name="wifi"
                        size={12}
                        color="black"
                        style={{ marginRight: 4 }}
                      />
                      <Text style={styles.iconLabel}>
                        {getSpeedInMbps(uploadTimeAndSpeed?.uploadSpeed)}
                      </Text>
                    </View>
                    <Text style={{ color: "#DDDDDD" }}> | </Text>
                    {/* Time View */}
                    <View style={styles.iconContainer}>
                      {/* <MCIcon
                        name="clock-outline"
                        size={12}
                        color="black"
                        style={{ marginRight: 4 }}
                      /> */}
                      <Text style={[styles.iconLabel, { fontStyle: "italic" }]}>
                        {getTimeInMinAndSec(
                          uploadTimeAndSpeed?.secondsRemaining
                        )}{" "}
                        left
                      </Text>
                    </View>
                  </View>
                )}
              </View>
            </View>
          </View>

          <View
            style={[styles.progressBarView, { justifyContent: "flex-start" }]}
          >
            <Text style={styles.infoText}>
              Once the upload is done, we will let you know.
            </Text>
          </View>
        </View>
        <View />
      </View>
      {/* Button View */}
      {/* {false && ( */}
      <View style={styles.goToHomeScreenView}>
        <PrimaryButton
          onPress={async () => {
            Orientation.lockToPortrait();
            await showActivity();
            Orientation.lockToPortrait();
            navigation.navigate("WithQuote");
          }}
          style={{
            backgroundColor: Colors.digitYellow,
            alignSelf: "flex-end",
            marginRight: 26,
          }}
        >
          {"Go to Homescreen"}
        </PrimaryButton>
      </View>
    </View>
  );
};
const styles = StyleSheet.create({
  main: {
    flex: 1,
    backgroundColor: "#FFFFFF",
  },
  gifView: {
    flex: 0.4,
    justifyContent: "center",
    alignItems: "center",
  },
  progressView: {
    flex: 0.5,
    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: 16,
    marginTop: 10,
    justifyContent: "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: 10,
    fontFamily: "Muli-Regular",
  },
  componentView: {
    flex: 0.85,
    flexDirection: "row",
    justifyContent: "space-between",
    marginHorizontal: 16,
  },
  goToHomeScreenView: {
    flex: 0.1,
    justifyContent: "center",
  },
  blankView: {
    // flex: 0.1,
  },
  progressBarView: {
    flex: 0.5,
    justifyContent: "center",
  },
  infoText: {
    fontFamily: "Muli-Bold",
    fontSize: 14,
    justifyContent: "center",
  },
});
export default VideoPIProgress;
