import React, { useEffect, useRef, useState, useReducer } from "react";
import {
  StyleSheet,
  View,
  Text,
  TouchableOpacity,
  Image,
  Button,
  LogBox,
  StatusBar,
  Linking,
  BackHandler,
  useWindowDimensions,
  Dimensions,
  FlatList,
  Animated,
  Alert,
} from "react-native";
import Header from "react-native-digitcamera/src/Screens/Header";
// import FirstRoute from "./FirstRoute";
// import SecondRoute from "./SecondRoute";
import { TabView, SceneMap, TabBar } 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 { useIsFocused } from "@react-navigation/native";
import { ProgressBar } from "react-native-paper";
import MCIcon from "react-native-vector-icons/MaterialCommunityIcons";
import Database from "../../../../../Components/common/DAsyncStorage";
import style from "react-native-digitcamera/src/common/CommonStyle";
import Colors from "react-native-digitcamera/src/common/Colors";
import InProgressSceneView from "react-native-digitcamera/src/Screens/MultiActivity/Scenes/InProgressSceneView";
import CompletedSceneView from "react-native-digitcamera/src/Screens/MultiActivity/Scenes/CompletedSceneView";

//Constants
const SCREEN_WIDTH = Math.round(Dimensions.get("window").width);
const SCREEN_HEIGHT = Math.round(Dimensions.get("window").height);
var docProgress = 0;
var interval;
// const MediaStatusSchemaX = [
//   {
//     activityId: "string",
//     activityTypeId: "string",
//     policyNumber: "23876847",
//     registrationNumber: "string",
//     activityStatus: "PENDING", // PENDING, IN-PROGRESS, COMPLETED
//     mode: "ONLINE", // ONLINE, OFFLINE
//     mediaUpload: MediaUpload,
//   },
//   {
//     activityId: "string",
//     activityTypeId: "string",
//     policyNumber: "0932898",
//     registrationNumber: "string",
//     activityStatus: "IN-PROGRESS", // PENDING, IN-PROGRESS, COMPLETED
//     mode: "OFFLINE", // ONLINE, OFFLINE
//     mediaUpload: MediaUpload,
//   },
//   {
//     activityId: "string",
//     activityTypeId: "string",
//     policyNumber: "8927398",
//     registrationNumber: "string",
//     activityStatus: "IN-PROGRESS", // PENDING, IN-PROGRESS, COMPLETED
//     mode: "OFFLINE", // ONLINE, OFFLINE
//     mediaUpload: MediaUpload,
//   },
//   {
//     activityId: "string",
//     activityTypeId: "string",
//     policyNumber: "9823798",
//     registrationNumber: "string",
//     activityStatus: "COMPLETED", // PENDING, IN-PROGRESS, COMPLETED
//     mode: "ONLINE", // ONLINE, OFFLINE
//     mediaUpload: MediaUpload,
//   },
//   {
//     activityId: "string",
//     activityTypeId: "string",
//     policyNumber: "2398732",
//     registrationNumber: "string",
//     activityStatus: "COMPLETED", // PENDING, IN-PROGRESS, COMPLETED
//     mode: "ONLINE", // ONLINE, OFFLINE
//     mediaUpload: MediaUpload,
//   },
// ];
var MediaStatusSchema = [];
let inProgressData = [];
let completedData = [];
var uploadedArray = [];
var unsubscribeNetInfo;
const MediaUpload = {
  status: "string", //uploading,failed,uploaded
  uri: "string",
  imageName: "string",
};

// FirstRoute and SecondRoute are written externally to handle more amount of data synchronously

const FirstRoute = () => <InProgressSceneView />;

const SecondRoute = () => <CompletedSceneView />;

const ActivityScreen = ({ navigation, route }) => {
  const layout = useWindowDimensions();
  const [isInternetConnected, SetIsInternetConnected] = useState(true);
  const [isStatus, setIsStatus] = useState(true);
  const [index, setIndex] = React.useState(0);
  const [uploadTimeAndSpeed, setUploadTimeAndSpeed] = useState({
    uploadSpeed: 0,
    secondsRemaining: 0,
  });
  // const car = require("../common/Image/new/four_wheeler.png");
  const car = require("../../common/Image/new/four_wheeler.png");

  const [routes] = React.useState([
    { key: "first", title: "In-Progress" },
    { key: "second", title: "Completed" },
  ]);

  const renderScene = SceneMap({
    first: FirstRoute,
    second: SecondRoute,
  });

  useEffect(async () => {
    if (!interval) {
      interval = setInterval(async () => {
        setTime();
        try {
          MediaStatusSchema = await Database.get("PIMediaStatus");
        } catch (error) {
          console.log("Error in ActivityScreen.js useEffect : ", error);
        }
      }, 1000);
    }
    try {
      MediaStatusSchema = await Database.get("PIMediaStatus");
      if (MediaStatusSchema) {
        MediaStatusSchema = await Database.get("PIMediaStatus");
        console.log(
          "MediaStatusSchema ActivityScreen.js ",
          JSON.stringify(MediaStatusSchema, null, " ")
        );
        var uploadedActivity = MediaStatusSchema.filter((activity) => {
          return activity.activityStatus == "COMPLETED";
        });
        console.log(
          "ActivityScreen.js : COMPLETED ACTIVITY :",
          JSON.stringify(uploadedActivity, null, "  ")
        );
        var allActivity = [];
        var updatedActivityWithProgress = MediaStatusSchema.filter(
          (activity) => {
            var uploadedImage = [];
            var uploadingImages = [];
            var failedImages = [];
            if (activity.activityStatus == "IN-PROGRESS") {
              // not using map,filter becouse require serial exicutions
              for (var uploadingDoc of activity.mediaUpload) {
                if (uploadingDoc.status == "uploading") {
                  uploadingImages.push(uploadingDoc);
                } else if (uploadingDoc.status === "uploaded") {
                  uploadedImage.push(uploadingDoc);
                } else {
                  failedImages.push(uploadingDoc);
                }
              }
              console.log(
                "ActivityScreen.js uploadedImage : ",
                uploadedImage.length,
                " uploadingImages : ",
                uploadingImages.length,
                " failedImages: ",
                failedImages.length
              );
              var progress =
                uploadedImage.length /
                (uploadedImage.length +
                  uploadingImages.length +
                  failedImages.length);
              docProgress = progress;
              console.log("ActivityScreen.js progress : ", progress);
              allActivity.push({
                ...activity,
                imageProgress: isNaN(progress) ? 0 : progress,
              });
              console.log(
                "******* EEEE EEE EE EEEE",
                JSON.stringify(allActivity, null, "  ")
              );
            } else {
              return allActivity.push({
                ...activity,
                imageProgress: isNaN(progress) ? 0 : progress,
              });
            }
          }
        );
        // setting all data in DB
        await Database.set("PIMediaStatus", allActivity);
        const alog = await Database.get("PIMediaStatus");
        console.log(
          "ActivityScreen AfterProgress update PIMediaStatus",
          JSON.stringify(alog, null, "  ")
        );
      }
      unsubscribeNetInfo = NetInfo.addEventListener(async (state) => {
        if (isInternetConnected != null) {
          if (isInternetConnected && (await checkInternetSpeed())) {
            console.log("isInternetConnected is true  in Activityscreen");
            setIsStatus("Uploading");
            SetIsInternetConnected(true);
          } else {
            console.log("isInternetConnected is false in Activityscreen");
            setIsStatus("Upload Paused");
            SetIsInternetConnected(false);
          }
        }
      });
      // const getEstimatedTime = (loaded, total) => {
      //   var seconds_elapsed =
      //     (new Date().getTime() - started_at.getTime()) / 1000;
      //   var bytes_per_second = seconds_elapsed ? loaded / seconds_elapsed : 0;
      //   var Kbytes_per_second = bytes_per_second / 1024;
      //   var remaining_bytes = total - loaded;
      //   var seconds_remaining = seconds_elapsed
      //     ? remaining_bytes / bytes_per_second
      //     : "calculating";
      //   console.log(
      //     "seconds_remaining:: ",
      //     Kbytes_per_second,
      //     seconds_remaining
      //   );
      //   return {
      //     uploadSpeed: Kbytes_per_second,
      //     secondsRemaining: seconds_remaining,
      //   };
      // };
    } catch (error) {
      console.log("Error in useEffect : ", error);
    }
    return () => {
      unsubscribeNetInfo && unsubscribeNetInfo();
    };
  }, [MediaStatusSchema]);
  const setTime = () => {
    const started_at = new Date();

    var seconds_elapsed = (new Date().getTime() - started_at.getTime()) / 1000;
    var bytes_per_second = seconds_elapsed
      ? uploadedArray.length / seconds_elapsed
      : 0;
    var Kbytes_per_second = bytes_per_second / 1024;
    var remaining_bytes = item.mediaUpload.length - uploadedArray.length;
    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);
  };

  const _renderTabBar = (props) => {
    return (
      <TabBar
        {...props}
        style={{ backgroundColor: "white" }}
        indicatorStyle={{
          borderBottomWidth: 2,
          borderColor: Colors.digitYellow,
        }}
        renderLabel={({ route, color }) => (
          <Text
            style={[
              style.muliBoldDB,
              { fontSize: 14, textTransform: "uppercase", color: color },
            ]}
          >
            {route.title}
          </Text>
        )}
        activeColor={"rgba(0, 0, 0, 1)"}
        inactiveColor={"rgba(0, 0, 0, 0.4)"}
      />
    );
  };

  return (
    <View style={styles.main}>
      <Header
        customTitle={"Activity Status"}
        hideArrowBackButton={false}
        onlanguagechange={() => {
          forceUpdate();
        }}
        onbackPress={() => {
          if (navigation.canGoBack()) {
            navigation.navigate("ActivityStatusScreen");
          } else {
            if (Platform.OS === "android") {
              Alert.alert("Close", "are you sure ?", [
                {
                  text: "Yes",
                  onPress: () => {
                    BackHandler.exitApp();
                  },
                  style: "cancel",
                },
                {
                  text: "No",
                  onPress: () => {
                    console.log("on No pressed");
                  },
                },
              ]);
            }
          }
        }}
      />

      <View style={{ flex: 1, justifyContent: "space-between" }}>
        {isInternetConnected ? null : (
          <View
            style={{
              flex: 0.3,
              flexDirection: "row",
              backgroundColor: "#FFFAEB",
              padding: 12,
              // height: 64,
            }}
          >
            <View style={{ flex: 0.1, flexDirection: "column" }}>
              <MCIcon
                name="wifi-off"
                size={20}
                color="red"
                style={{ marginRight: 4 }}
              />
            </View>
            <View style={{ flex: 0.9, flexDirection: "column" }}>
              <Text style={{ fontSize: 12, fontFamily: "Muli-Bold" }}>
                Poor Network - Uploads paused
                {"\n"}
              </Text>
              <Text style={{ fontSize: 12 }}>
                We'll resume upload when network connection is back. Meanwhile
                you can continue using your phone.
              </Text>
            </View>
          </View>
        )}
        <TabView
          lazy={({ route }) => route.key === "second"}
          navigationState={{ index, routes }}
          renderScene={renderScene}
          renderTabBar={_renderTabBar}
          onIndexChange={setIndex}
          initialLayout={{ width: layout.width }}
          style={{ flex: 0.9 }}
        />
        <View
          style={{
            flex: 0.1,
            marginHorizontal: 16,
            justifyContent: "center",
          }}
        >
          <PrimaryButton
            onPress={async () => {
              interval && clearInterval(interval);
              navigation.pop();
            }}
          >
            {"Go to Homepage"}
          </PrimaryButton>
        </View>
      </View>
    </View>
  );
};

export default ActivityScreen;

const styles = StyleSheet.create({
  main: {
    flex: 1,
    backgroundColor: "#FFFFFF",
  },
  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,
  },
  tabBar: {
    flexDirection: "row",
  },
  tabItem: {
    flex: 1,
    alignItems: "center",
    padding: 16,
  },
});
