import React, { useEffect, useState, useCallback } from "react";
import {
  StyleSheet,
  View,
  Text,
  TouchableOpacity,
  Image,
  Button,
  LogBox,
  StatusBar,
  Linking,
  BackHandler,
  useWindowDimensions,
  Dimensions,
  Alert,
  FlatList,
  Platform,
} from "react-native";
import Header from "react-native-digitcamera/src/Screens/Header";
// import FirstRoute from "./FirstRoute";
// import SecondRoute from "./SecondRoute";
import { TabView, SceneMap } from "react-native-tab-view";
import {
  TextInput,
  PrimaryButton,
  NewRoundButton,
  Spinner,
  NewRadioButton,
} from "../../common/ThemedComponents";
import NetInfo from "@react-native-community/netinfo";
import { checkInternetSpeed } from "react-native-digitcamera/src/Screens/OfflineFlow/CommonFunc";
import { useFocusEffect, useIsFocused } from "@react-navigation/native";
import MCIcon from "react-native-vector-icons/MaterialCommunityIcons";
import { ProgressBar } from "react-native-paper";
import Toturial from "react-native-digitcamera/src/Screens/Toturial";
import Database from "../../../../../Components/common/DAsyncStorage";
import { ScrollView } from "react-native-gesture-handler";
import { async } from "validate.js";
import { useDispatch, useSelector } from "react-redux";
import Orientation from "react-native-orientation";
import { NamedModal } from "react-native-digitcamera/src/common/GlobalModal";
import DeviceInfo from "react-native-device-info";

//Constants
const SCREEN_WIDTH = Math.round(Dimensions.get("window").width);
const SCREEN_HEIGHT = Math.round(Dimensions.get("window").height);

let updateInterval;
const ActivityStatusScreen = ({ navigation, route }) => {
  const isFocused = navigation.isFocused();

  const layout = useWindowDimensions();
  const [isInternetConnected, setInternetConnected] = useState(true);
  const [isStatus, setIsStatus] = useState(true);
  const [docProgress, setDocProgress] = useState(0);
  const [uploadTimeAndSpeed, setUploadTimeAndSpeed] = useState({
    uploadSpeed: 0,
    secondsRemaining: 0,
  });
  const [username, setUsername] = useState("");
  const [inProgressLength, setProgressLength] = useState(0);

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

  useEffect(() => {
    if (isInternetReachable === true) {
      setInternetConnected(true);
    } else if (isInternetReachable === false) {
      setInternetConnected(false);
    }
  }, [isInternetReachable]);

  const dispatch = useDispatch();

  const location_status = useSelector((state) => state.AppPermissions.location);

  const getFlag = () => {
    if (location_status === "GRANTED") {
      return true;
    }
    return false;
  };

  useFocusEffect(
    useCallback(() => {
      Orientation.lockToPortrait();
      setCustomerName();
      validateIsFromLink();
      updateInterval = setInterval(() => {
        updateData();
      }, 1000);
      return () => {
        clearInterval(updateInterval);
      };
    }, [])
  );

  useEffect(() => {
    Orientation.lockToPortrait();
  }, []);

  const validateIsFromLink = async () => {
    var PIDeeplink = await Database.get("PIDeeplink");
    var PIVechicleData = await Database.get("PIVechicleData");

    var isFromLink = PIDeeplink.isFromLink;
    console.log(
      "validateIsFromLink  >>> from ActivityStatusScreen.js isFromLink ",
      isFromLink
    );
    if (isFromLink) {
      navigation.navigate("Toturial", {
        activityId: PIVechicleData?.activityId,
        activityTypeId: PIVechicleData?.activityTypeId,
        licensePlateNumber: PIVechicleData?.licensePlateNumber,
      });
    }
  };
  const setCustomerName = async () => {
    console.log("settinname");
    const CustomerDetails = await Database.get("CustomerDetails");
    if (CustomerDetails) {
      setUsername(CustomerDetails?.name);
    } else {
      setUsername("User");
    }
  };

  const updateData = async () => {
    try {
      console.log("updateDataa");
      // mediaStatusArray = await Database.get("PIMediaStatus");
      // inProgressArray = [];

      const pMediaStatus = await Database.get("PIMediaStatus");

      if (isInternetConnected) {
        setIsStatus("Uploading");
      } else {
        setIsStatus("Upload Paused");
      }

      const totalMediaLength = pMediaStatus.length;

      const completedLength = pMediaStatus.filter(
        (item) => item.activityStatus === "COMPLETED"
      ).length;
      const pInProgressLength = pMediaStatus.filter(
        (item) => item.activityStatus === "IN-PROGRESS"
      ).length;

      setProgressLength(pInProgressLength);

      let totalProgress = 0;

      if (completedLength && inProgressLength) {
        totalProgress = inProgressLength / (completedLength + inProgressLength);
      }

      console.log("progress", inProgressLength);

      setDocProgress(totalProgress);

      setTime(inProgressLength, totalMediaLength);

      // totalLength = mediaStatusArray.length;
      // completedArray = [];
      // inProgressArray = [];
      // for (var item of mediaStatusArray) {
      //   console.log("mediaStatusArray item &&&&&& ssss", JSON.stringify(item));
      //   if (item.activityStatus == "IN-PROGRESS") {
      //     inProgressArray.push(item);
      //   }
      //   if (item.activityStatus == "COMPLETED") {
      //     completedArray.push(item);
      //   }
      // }
      // console.log(
      //   "ActivityStatusScreen.js inProgressArray : ",
      //   inProgressArray.length
      // );
      // console.log(
      //   "ActivityStatusScreen.js completedArray : ",
      //   completedArray.length
      // );

      // inProgressLength = inProgressArray.length;
      // var tempDocProgress =
      //   completedArray.length /
      //   (completedArray.length + inProgressArray.length);
      // setDocProgress(tempDocProgress);
      // console.log("docProgress activitystatusscreen:::: ", docProgress);

      // const started_at = new Date();

      // var seconds_elapsed =
      //   (new Date().getTime() - started_at.getTime()) / 1000;
      // var bytes_per_second = seconds_elapsed
      //   ? totalLength / seconds_elapsed
      //   : 0;
      // var Kbytes_per_second = bytes_per_second / 1024;
      // var remaining_bytes = inProgressLength - totalLength;
      // var seconds_remaining = seconds_elapsed
      //   ? remaining_bytes / bytes_per_second
      //   : "calculating";
      // console.log("seconds_remaining:: ", Kbytes_per_second, seconds_remaining);
      // var time = {
      //   uploadSpeed: Kbytes_per_second,
      //   secondsRemaining: seconds_remaining,
      // };
      // console.log("time:: ****", time);
      // setUploadTimeAndSpeed(time);
    } catch (error) {
      console.log("error in activitystatuscreen.js updateData() ", error);
    }
  };
  const getTimeInMinAndSec = (sec) => {
    if (!sec || sec === "calculating") {
      return `0 sec`;
    }

    const min = sec / 60;
    const remSec = sec % 60;
    return `${Math.floor(min)} min ${Math.floor(remSec)} sec`;
  };

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

  const setTime = (inProgressLength, totalMediaLength) => {
    const started_at = new Date();
    let seconds_elapsed = (new Date().getTime() - started_at.getTime()) / 1000;
    let bytes_per_second = seconds_elapsed
      ? totalMediaLength / seconds_elapsed
      : 0;
    let Kbytes_per_second = bytes_per_second / 1024;
    let remaining_bytes = inProgressLength - totalMediaLength;
    let seconds_remaining = seconds_elapsed
      ? remaining_bytes / bytes_per_second
      : "calculating";
    console.log("seconds_remaining:: ", Kbytes_per_second, seconds_remaining);
    let time = {
      uploadSpeed: Kbytes_per_second,
      secondsRemaining: seconds_remaining,
    };
    console.log("time:: ****", time);
    setUploadTimeAndSpeed(time);
  };

  const onHandleBtnPress = () => {
    DeviceInfo.isLocationEnabled().then((enable) => {
      if (!enable) {
        if (Platform.OS == "android") {
          const LocationEnabler =
            require("react-native-location-enabler").default;
          const {
            PRIORITIES: { BALANCED_POWER_ACCURACY },
            requestResolutionSettings,
          } = LocationEnabler;
          requestResolutionSettings({
            priority: BALANCED_POWER_ACCURACY,
            alwaysShow: true, //
            needBle: false, //
          });
        }
      } else {
        onLocationServiceEnabled();
      }
    });
    const onLocationServiceEnabled = async () => {
      console.log("*** ActivityStatusScreen interval onHandleBtnPress");
      clearInterval(updateInterval);
      console.log("on handle btn press");
      // navigate to WithQuote
      await Database.update("PICanShowActivity", {
        isShowActivityScreen: false,
      });
      var AppLoginStatus = await Database.get("AppLoginStatus");

      if (AppLoginStatus?.userType == "OEMDealer") {
        //VehicleInspection
        route.params.props.navigation.navigate(
          route.params.navigateBackToPostplanPreviousPolicy
        );
      } else {
        navigation.navigate("WithQuote");
      }
    };
  };
  return (
    <View style={[styles.main, { backgroundColor: "#EAEAEA" }]}>
      <Header
        customTitle={"  Activity Status"}
        hideArrowBackButton={true}
        shiftTitleToLeft={true}
        onlanguagechange={() => {
          forceUpdate();
        }}
        onbackPress={onHandleBtnPress}
      />

      <ScrollView>
        <View
          style={{
            flex: 0.2,
            flexDirection: "row",
            padding: 16,
            backgroundColor: "white",
          }}
        >
          <View
            style={{
              flex: 1,
              flexDirection: "column",
            }}
          >
            <Text style={styles.heading}>
              Welcome {username},{"\n"}
            </Text>
            <Text style={styles.paragraph}>You can shoot video of car</Text>
          </View>
        </View>
        <View
          style={{
            flex: 0.8,
            flexDirection: "row",
          }}
        >
          <View style={{ flex: 1, flexDirection: "column" }}>
            <View style={[{ flex: 0.6, flexDirection: "row" }, styles.box]}>
              <View style={{ flex: 1, flexDirection: "column" }}>
                <View
                  style={{
                    flex: 0.6,
                    flexDirection: "row",
                    width: "100%",
                    height: SCREEN_HEIGHT / 4,
                    // backgroundColor: "red",
                  }}
                >
                  <Image
                    source={{
                      uri: "https://d2h44aw7l5xdvz.cloudfront.net/CRM/PRM/selfie_car.png",
                    }}
                    resizeMode={"contain"}
                    style={{ width: "100%", height: "100%" }}
                  />
                </View>
                <View style={{ flex: 0.4, flexDirection: "row", padding: 5 }}>
                  <View style={{ flex: 1, flexDirection: "column" }}>
                    <View style={{ flex: 0.33, flexDirection: "row" }}>
                      <Text style={styles.heading}>Shoot Video</Text>
                    </View>
                    <View
                      style={{ flex: 0.33, flexDirection: "row", padding: 5 }}
                    >
                      {/* <Text>
                      Lorem ipsum scing elit. Suspend isse justo, facilisis eget
                      porta.
                    </Text> */}
                    </View>
                    <View
                      style={{
                        flex: 0.33,
                        flexDirection: "row",
                        marginBottom: 12,
                      }}
                    >
                      <PrimaryButton
                        onPress={onHandleBtnPress}
                        disabled={!getFlag()}
                      >
                        {"Start"}
                      </PrimaryButton>
                    </View>
                  </View>
                </View>
              </View>
            </View>

            {getFlag() && (
              <View
                style={[
                  {
                    flex: 0.2,
                    flexDirection: "row",
                  },
                  styles.box,
                ]}
              >
                <TouchableOpacity
                  style={{ flex: 1, flexDirection: "column" }}
                  onPress={() => {
                    console.log(
                      "*** ActivityStatusScreen interval touchable opacity before activityScreen"
                    );
                    clearInterval(updateInterval);
                    /* Don't know what is this need more clearance */
                    navigation.navigate("ActivityScreen");
                  }}
                >
                  <View style={{ flex: 0.5, flexDirection: "row" }}>
                    <Text style={{ fontFamily: "Muli-Bold", fontSize: 16 }}>
                      Activity Status
                    </Text>
                  </View>
                  {inProgressLength > 0 ? (
                    <View style={{ flex: 0.5, flexDirection: "row" }}>
                      <View style={{ flex: 1, flexDirection: "column" }}>
                        <ProgressBar
                          progress={
                            isNaN(docProgress) ||
                            docProgress == undefined ||
                            docProgress == null
                              ? 0
                              : docProgress
                          }
                          color={"#FFBB00"}
                          style={{
                            height: 4,
                            borderRadius: 12,
                            backgroundColor: "#F5F5F5",
                          }}
                        />

                        <View
                          style={{
                            flex: 0.5,
                            flexDirection: "row",
                            marginTop: 2,
                          }}
                        >
                          <View style={{ flex: 1, flexDirection: "column" }}>
                            <View style={{ flex: 1, flexDirection: "row" }}>
                              <Text
                                style={{
                                  flex: 0.33,
                                  flexDirection: "column",
                                }}
                              >
                                {inProgressLength} Uploading
                              </Text>
                              <MCIcon
                                name="wifi"
                                size={16}
                                color="#EE0000"
                                style={{ marginRight: 4 }}
                              />
                              <Text
                                style={{
                                  flex: 0.33,
                                  flexDirection: "column",
                                }}
                              >
                                {getSpeedInMbps(
                                  uploadTimeAndSpeed?.uploadSpeed
                                )}
                              </Text>
                              <Text
                                style={{
                                  flex: 0.33,
                                  flexDirection: "column",
                                  fontStyle: "italic",
                                }}
                              >
                                {getTimeInMinAndSec(
                                  uploadTimeAndSpeed?.secondsRemaining
                                )}{" "}
                                left
                              </Text>
                            </View>
                          </View>
                        </View>
                      </View>
                    </View>
                  ) : (
                    <View style={{ flex: 0.5, flexDirection: "row" }}>
                      <View
                        style={{
                          flex: 1,
                          flexDirection: "column",
                          paddingTop: 8,
                        }}
                      >
                        <Text
                          style={{
                            color: "#444444",
                            fontSize: 13,
                            fontFamily: "Muli-Regular",
                          }}
                        >
                          You can view video upload status here
                        </Text>

                        <View
                          style={{
                            flex: 0.5,
                            flexDirection: "row",
                            marginTop: 2,
                          }}
                        >
                          <View
                            style={{
                              flex: 1,
                              flexDirection: "column",
                              paddingTop: 8,
                            }}
                          >
                            <View style={{ flex: 1, flexDirection: "row" }}>
                              <Text
                                style={{
                                  flex: 0.33,
                                  flexDirection: "column",
                                  fontFamily: "Muli-Bold",
                                  fontSize: 11,
                                }}
                              >
                                No Uploads
                              </Text>
                            </View>
                          </View>
                        </View>
                      </View>
                    </View>
                  )}

                  <View style={{ flex: 0.33, flexDirection: "row" }} />
                </TouchableOpacity>
              </View>
            )}
            <View
              style={{
                flex: 0.2,
                flexDirection: "row",
              }}
            />
          </View>
        </View>
      </ScrollView>
    </View>
  );
};
export default ActivityStatusScreen;

const styles = StyleSheet.create({
  main: {
    flex: 1,
    backgroundColor: "#FFFFFF",
  },
  box: {
    borderWidth: 1,
    borderColor: "#DDDDDD",
    margin: 12,
    padding: 12,
    shadowColor: "#DDDDDD",
    shadowOpacity: 0.16,
    borderRadius: 8,
    backgroundColor: "#ffffff",
  },
  paragraph: {
    fontSize: 18,

    // textAlign: "center",
  },
  heading: {
    fontSize: 22,
    alignSelf: "flex-start",
    fontFamily: "Muli-Bold",
  },
  subView: {
    margin: 18,
    flex: 1,
  },
  ThankYoumsgView: {
    flex: 0.95,
  },
  needHelpView: {
    flex: 0.15,
    marginTop: 48,
  },
  thankyoumsg: {
    marginLeft: 6,
    marginRight: 6,
    marginTop: 33,
    flex: 1,
  },
  allDoneText: {
    fontFamily: "Muli-Black",
    fontSize: 20,
  },
  PImsg: {
    fontSize: 16,
    fontFamily: "Muli-SemiBold",
    marginTop: 8,
  },
  needHelpText: {
    fontFamily: "Muli-ExtraBold",
    fontSize: 12,
    color: "#999999",
  },
  buttonStyle: {
    height: 40,
    marginLeft: 6,
    marginRight: 6,
    borderColor: "#444444",
    borderWidth: 1,
    borderRadius: 4,
    marginTop: 12,
    flexDirection: "row",
    alignItems: "center",
    marginBottom: 4,
  },
  buttonText: {
    fontFamily: "Muli-Bold",
    fontSize: 16,
    marginLeft: 16,
  },
});
