import React, { useEffect, useMemo, useRef, useState } from "react";
import {
  StyleSheet,
  View,
  Image,
  Text,
  StatusBar,
  FlatList,
  BackHandler,
  Alert,
  Dimensions,
  ImageBackground,
  useColorScheme,
} from "react-native";
import {
  ACTIVITY_TYPE_MOTOR_CVOD_PRE_INSPECTION_SELF_SURVEY,
  CHASSIS_NUMBER,
  SELFI_IMAGE_HN,
  VIDEO_TITLE_HN,
  SELFI_IMAGE,
  VIDEO_TITLE,
  get4WPoseFileNames,
  DOC,
  detectOnlyPoseFileNames,
  multiplePics,
  get2WPoseFileNotDoc,
  image_pose_blur,
  image_pose_dark,
  image_pose_wrong,
  is2Wflow,
} from "react-native-digitcamera/src/common/Constants";
// import { translate } from "react-native-digitcamera/src/common/localize/i18n";
import Orientation from "../../../react-native-orientation";
// import Geolocation from "@react-native-community/geolocation";
// import { getTimeZone } from "react-native-localize";
// import { TouchableOpacity } from "react-native-gesture-handler";
// import RNFetchBlob from "rn-fetch-blob";
// import { SELFSURVEYSERVICE_DOCUMENT_URL } from "react-native-digitcamera/src/Api/ApiUrls";
// import ViewShot, { captureRef } from "react-native-view-shot";
// import VideoPlayer from "react-native-video-player";
import Header from "./Header";
import { PrimaryButton, Spinner } from "../common/ThemedComponents";
import Database from "../../../../Components/common/DAsyncStorage";
import debounce from "lodash.debounce";
import { useSelector, useDispatch } from "react-redux";
import NetInfo from "@react-native-community/netinfo";
// import { poseDetection } from "react-native-digitcamera/src/common/Services/poseDetection";
// import reactotron from "reactotron-react-native";
// import { chassiesPoseDetetction } from "react-native-digitcamera/src/common/Services/chassisPoseDetection";
import Modal from "../common/Modal";
import { getDimension } from "../common/scaling";
// import DeviceInfo from "react-native-device-info";
// const { getImei } = require("react-native-imei");
// // import moment from "moment";
import {
  errorRecord,
  firebaseAttributes,
} from "react-native-digitcamera/src/common/libEventLog/libCrashlytics/libCrashlyticsEvent";

const { SCREEN_HEIGHT, SCREEN_WIDTH } = getDimension();

import {
  UELogEvent,
  UELogMessage,
} from "../common/libEventLog/UserExperior/LibUserExperior";
import { isCVFlow } from "react-native-digitcamera/src/common/Constants";
import UploadFile from "react-native-digitcamera/src/Screens/UploadFile";
import { useFocusEffect, useIsFocused } from "@react-navigation/native";

import {
  callChassisPoseDetection,
  callPoseDetection,
  canCreateActivityId,
  canUpload,
  getCurrentActivity,
  offlinePIDataToRealm,
} from "react-native-digitcamera/src/Screens/OfflineFlow/CommonFunc";
import { getActivityid } from "react-native-digitcamera/src/common/Services/getActivityid";
import { BackgroundUploadFile2WOffline } from "react-native-digitcamera/src/Screens/SilentUpload/SilentUploadUtils";
import { setCreateActivity } from "react-native-digitcamera/src/common/OfflineActivityListener";
import { useCallback } from "react";
import { chassiesPoseDetetction } from "react-native-digitcamera/src/common/Services/chassisPoseDetection";
import { checkPoseDetection } from "react-native-digitcamera/src/common/poseDetection";
// import { async } from "validate.js";
// import { retryImageAction } from "react-native-digitcamera/src/redux/actions/retryImageAction";
const DEBOUNCE_INTERVAL = 500;

var RealmData;
var PIVechicleData;
var AppLoginStatus;
var activityId;
var activityTypeId;
var licensePlateNumber;
const no_internet = require("../common/Image/no_internet.png");
var PIRetryCount;

var sensorImageDetails = [];
var PILocation;
var isFocused;

let interval;

const InvalidImages = ({ navigation, route }) => {
  const [isposeDetectionCompleted, setIsposeDetectionCompleted] =
    useState(true);
  const [invalidData, setInvalidData] = useState([]);
  const [isInternetConnected, SetIsInternetConnected] = useState(true);
  const [onRetryClick, SetOnRetryClick] = useState(false);
  const [isOfflineLoading, SetIsOfflineLoading] = useState(false);
  const RetryCountData = useSelector((state) => state.RetryCountData);
  const [failure, setFailure] = useState(false);

  const dispatch = useDispatch();
  isFocused = useIsFocused();

  const enableCreateActivity = () => {
    dispatch({
      type: "DISABLE_CREATE_ACTIVITY",
    });
  };
  useEffect(() => {
    enableCreateActivity();
    let unsubscribe = navigation.addListener("focus", () => {
      Orientation.lockToPortrait();
    });
    return unsubscribe();
  }, []);

  const internetChangeListener = useMemo(async () => {
    if (!isInternetConnected) {
      // if internet not connected
      SetOnRetryClick(false);
    } else {
      SetOnRetryClick(true);
    }
  }, [!isInternetConnected]);

  useEffect(() => {
    interval = setInterval(() => {
      getInvalidImagesData();
    }, 1000);
  }, []);

  useEffect(() => {
    var unsubscribe;
    var netInfoSubscription;
    var backHandler;
    const asyncLogic = async () => {
      RealmData = await Database.get("SelectedLang");
      PIVechicleData = await Database.get("PIVechicleData");
      AppLoginStatus = await Database.get("AppLoginStatus");
      PIRetryCount = await Database.get("PIRetryCount");
      PILocation = await Database.get("PILocation");

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

      netInfoSubscription = NetInfo.addEventListener((state) => {
        if (state && isFocused) {
          Orientation.lockToPortrait();
          if (state.isInternetReachable) {
            SetOnRetryClick(true);
          } else {
            SetIsInternetConnected(false);
            SetOnRetryClick(false);
            UELogEvent("Offline Flow : invalidImages.js", {
              mode: "offline",
            });
          }
        }
      });

      // disabled back handler
      backHandler = BackHandler.addEventListener("hardwareBackPress", () => {
        return true;
      });
    };
    asyncLogic();
    return () => {
      unsubscribe && unsubscribe();
      netInfoSubscription && netInfoSubscription();
      backHandler && backHandler.remove();
    };
  }, []);

  // useFocusEffect(
  //   useCallback(() => {
  //     console.log("oooo o oo o o o o o o o ");
  //     Orientation.lockToPortrait();
  //   }, [])
  // );
  const getInvalidImagesData = async () => {
    try {
      const VehicleInstructions = await Database.get("PIVechicleInstruction"); // all instruction
      const instructions = JSON.parse(VehicleInstructions.instuction);
      const mediaStatus = await Database.get("PIMediaStatus"); // failed and uploaded images
      var currentActivity = await getCurrentActivity();
      var imageMedia = currentActivity.mediaUpload;
      if (instructions && mediaStatus) {
        if (instructions.length != 0 && imageMedia.length != 0) {
          //failed images
          const failedImagesData = imageMedia.filter(
            (item) => item?.status == "poseFailed" || item?.status == "failed"
          );

          // navigate to progress
          if (failedImagesData.length == 0 && PIRetryCount?.retryCount > 0) {
            clearInterval(interval);
            // BackgroundUploadFile2WOffline();
            navigation.navigate("ActivityScreen");
          }

          if (imageMedia.length > 0) {
            if (PIRetryCount?.retryCount <= 0) {
              var isUploading = imageMedia.filter((item) => {
                return item?.status == "pending";
              });
              console.log(
                " isUploading isUploading isUploading isUploading",
                isUploading
              );
              if (isUploading.length == 0) {
                SetIsOfflineLoading(false);
              }
            }
          }
          //failed images with its instruction
          const invalidImagesData = [];
          instructions.forEach((item) => {
            const newObj = failedImagesData.find(
              (failedImageItem) =>
                failedImageItem.imageName === item.imageName &&
                !canUpload(failedImageItem.imageName)
            );
            if (newObj !== undefined) {
              item.imageUri = newObj.uri;
              // console.log(item);
              invalidImagesData.push(item);
            }
          });
          setInvalidData(invalidImagesData);
        }
      }
    } catch (error) {
      console.log("Error invalidImages.js getInvalidImagesData : ", error);
    }
  };

  const checkNavigation = async () => {
    try {
      const mediaStatus = await Database.get("PIMediaStatus"); // failed and uploaded images
      const PIVechicleData = await Database.get("PIVechicleData");

      var activityId = PIVechicleData?.activityId;

      var currentActivity = mediaStatus.filter((activity) => {
        return activity.activityId == activityId;
      });

      var imageMedia = currentActivity[0].mediaUpload;

      dispatch({
        type: "RETRY_COUNT",
        payload: {
          retryCount: Number(RetryCountData.retryCountInfo.retryCount) + 1,
          index: 0,
          isAddNewImageData: true,
        },
      });

      let piRetryCount = PIRetryCount?.retryCount;
      await Database.update("PIRetryCount", {
        retryCount: piRetryCount + 1,
        index: 0,
        isAddNewImageData: true,
      });

      await Database.update("PIINDEX", {
        lastIndex: 0,
      });

      dispatch({
        type: "LAST_DATA",
        payload: {
          isLast: false,
        },
      });

      const failedImagesData = imageMedia.filter(
        (item) =>
          item?.status == "poseFailed" ||
          item?.status == "failed" ||
          item?.status == "pending"
      );

      if (failedImagesData.length >= 0) {
        clearInterval(interval);
        navigation.navigate("PI");
      }
      // clearing data before going PI SCREEN
      // When we land on PI SCreen At that time we will get Clean Redux With NO Values
      // We are storing all Redux value in realm and We are using it from there only...
      dispatch({
        type: "CLEAR_RETRY_IMAGE_STATE",
      });

      await Database.update("PIPoseDetectionCompleted", {
        poseDetectionCompletedCount: 0,
      });
    } catch (error) {
      console.log("Error checkNavigation() :", error);
    }
  };

  const addSensorImageData = (ext, ImageStatus, imageName) => {
    var currentLatitude = PILocation?.lat;
    var currentLongitude = PILocation?.long;
    var attemptCount = PIRetryCount?.retryCount + 1;
    var fileName = activityId + "_" + imageName + ext;
    //adding sensor data
    sensorImageDetails.push({
      attemptCount: attemptCount,
      fileName: fileName,
      latitude: currentLatitude,
      longitude: currentLongitude,
      pose: imageName,
      success: ImageStatus,
      timestamp: new Date().getTime(),
    });
    dispatch({
      type: "SENSOR_DETAILS",
      payload: sensorImageDetails,
    });
  };
  const noInternetAlertUx = () => {
    return (
      <View>
        <View
          style={{
            justifyContent: "center",
            marginVertical: 10,
          }}
        >
          <Image
            source={no_internet}
            resizeMode="contain"
            style={{
              // resizeMode: "center",
              width: SCREEN_WIDTH - 128,
              alignItems: "center",
              height: SCREEN_HEIGHT * 0.4,
              alignSelf: "center",
            }}
          />
        </View>

        <View
          style={{
            alignSelf: "center",
            marginTop: 32,
          }}
        >
          <Text
            style={{
              fontFamily: "Muli-Regular",
              fontSize: 14,
            }}
          >
            {"Please recheck your Internet connection and Retry"}
          </Text>
        </View>
        <PrimaryButton
          style={{
            margin: 24,
          }}
          disabled={!onRetryClick}
          onPress={async () => {
            if (onRetryClick) {
              SetIsOfflineLoading(true);
              SetIsInternetConnected(true);
              // setFailure(!failure);
              if (interval) {
                clearInterval(interval);
              }
              await checkPose();
              interval = setInterval(() => {
                console.log(`[INVALID IMAGES] [ONPress - INTERVAL] ID`);
                getInvalidImagesData();
              }, 1000);
            }
          }}
        >
          {"Retry"}
        </PrimaryButton>
      </View>
    );
  };

  const checkPose = async () => {
    try {
      var activity = await getCurrentActivity();
      if (!canCreateActivityId(activity.activityId)) {
        checkPoseDetection();
      }
    } catch (error) {
      console.log("Error : in checkPose ", error);
    }
  };

  const noInternetAlert = () => {
    return (
      <View>
        <Modal
          isVisible={!isInternetConnected}
          // isVisible={false}
          onBackdropPress={() => SetIsInternetConnected(false)}
          onClose={() => SetIsInternetConnected(true)}
          heading={"No Internet Connection"}
          isTranslate={true}
          headerImageVisible={false}
        >
          {noInternetAlertUx()}
        </Modal>
      </View>
    );
  };

  const debouncedCall = debounce(
    () => {
      console.log("Debounced");
      checkNavigation();
    },
    DEBOUNCE_INTERVAL,
    {
      trailing: true,
    }
  );

  const renderItem = ({ item, index }) => {
    return (
      <View>
        <View style={styles.listView}>
          {/* Image View */}
          <View style={styles.imageView}>
            <Image
              source={{
                uri: item.imageUri,
                cache: "only-if-cached",
              }}
              style={{
                alignSelf: "center",
                width: SCREEN_WIDTH / 2.7,
                height: SCREEN_WIDTH / 2.9,
                resizeMode: "stretch",
              }}
            />
          </View>
          {/* Blank View */}
          <View style={styles.blankView} />
          {/* Text View */}
          <View style={styles.textView}>
            <Text style={styles.heading}>{item?.stepTitle}</Text>
            {/* <Text style={styles.subHeadingText}>{item.msg}</Text> */}
          </View>
        </View>
        <View style={styles.divider} />
      </View>
    );
  };
  // const isDarkMode = useColorScheme() === "dark";
  const isDarkMode = false;

  return (
    <View style={styles.main}>
      <StatusBar
        barStyle={isDarkMode ? "light-content" : "dark-content"}
        hidden={true}
      />
      <Spinner
        // loading={false}
        loading={isOfflineLoading}
      />
      <Header
        onlanguagechange={() => {
          forceUpdate();
        }}
        onbackPress={() => {
          navigation.goBack();
        }}
        shiftTitleToLeft={true}
      />
      {!isposeDetectionCompleted ? (
        <>
          <View
            style={{
              justifyContent: "center",
              alignItems: "center",
              flex: 1,
            }}
          >
            <Text style={styles.posemsgText}>
              We are processing your images please wait
            </Text>
          </View>
        </>
      ) : (
        <>
          {/* Document list  */}
          <View style={styles.subMainView}>
            <Text style={styles.oopsTitleText}>
              {"Oops!  "}
              <Text
                style={{
                  fontSize: 20,
                  color: "#000000",
                }}
              >
                {invalidData.length + " "}
                {"Incorrect photos"}
              </Text>
            </Text>
            <Text style={styles.subText}>
              {
                "Please upload the photo again! The photo uploaded is incorrect Please follow the instructions and capture it again"
              }
            </Text>

            <FlatList
              data={invalidData}
              keyExtractor={(item, index) => index.toString()}
              renderItem={renderItem}
              maxToRenderPerBatch={100}
              updateCellsBatchingPeriod={1000}
            />
          </View>
          {noInternetAlert()}
          {/* button view */}
          <View style={styles.buttonView}>
            <PrimaryButton
              onPress={() => {
                debouncedCall();
              }}
              // disabled={!isInternetConnected}
              disabled={false}
            >
              {"Retake"}
            </PrimaryButton>
          </View>
        </>
      )}
    </View>
  );
};

export default InvalidImages;

const styles = StyleSheet.create({
  main: {
    flex: 1,
    backgroundColor: "white",
  },
  subMainView: {
    flex: 0.9,
    marginHorizontal: 24,
  },
  buttonView: {
    flex: 0.1,
    marginLeft: 24,
    marginRight: 24,
    justifyContent: "center",
  },
  oopsTitleText: {
    fontFamily: "Muli-ExtraBold",
    fontSize: 20,
    color: "red",
    marginBottom: 10,
  },
  titleText: {
    fontFamily: "Muli-ExtraBold",
    fontSize: 20,
  },
  subText: {
    fontSize: 16,
    fontFamily: "Muli-Regular",
    marginBottom: 24,
  },
  imageView: {
    flex: 0.4,
    justifyContent: "center",
    borderColor: "#DDDDDD",
    borderWidth: 1,
    borderRadius: 8,
  },
  listView: {
    flex: 1,
    flexDirection: "row",
  },
  blankView: {
    flex: 0.05,
  },
  textView: {
    flex: 0.55,
    justifyContent: "center",
  },
  divider: {
    width: SCREEN_WIDTH,
    height: 1,
    borderWidth: 1,
    marginTop: 17,
    marginBottom: 17,
    borderColor: "#DDDDDD",
  },
  heading: {
    fontSize: 16,
    fontFamily: "Muli-Bold",
    marginBottom: 10,
  },
  subHeadingText: {
    fontSize: 13,
    fontFamily: "Muli-Regular",
    color: "#444444",
  },
  posemsgText: {
    fontSize: 16,
    fontFamily: "Muli-Regular",
    textAlignVertical: "center",
  },
});
