import React, { useEffect, useRef, useState } from "react";
const iOS = Platform.OS === "ios";
import {
  Alert,
  BackHandler,
  Image,
  Platform,
  StatusBar,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
} from "react-native";
import Colors from "react-native-digitcamera/src/common/Colors";
import { SafeAreaView } from "react-native-safe-area-context";
import VideoPlayer from "react-native-video-player";
import {
  SCREEN_HEIGHT,
  SCREEN_WIDTH,
} from "react-native-digitcamera/src/common/Constants";
import {
  PrimaryButton,
  Spinner,
} from "react-native-digitcamera/src/common/ThemedComponents";
import Orientation from "react-native-orientation";

/*@RCBPREVIEW*/
import { useDispatch } from "react-redux";
import style from "../../../../Components/common/CommonStyle";
import Icon from "react-native-vector-icons/MaterialCommunityIcons";
import {
  UELogEvent,
  UELogMessage,
} from "../common/libEventLog/UserExperior/LibUserExperior";
import NetInfo from "@react-native-community/netinfo";
import Database from "../../../../Components/common/DAsyncStorage";
import { CreateActivityId } from "react-native-digitcamera/src/Screens/OfflineFlow/CreateActivityId";
import { useMemo } from "react";
import { useIsFocused } from "@react-navigation/native";

const retake = require("../common/Image/retake.png");
const proceed = require("../common/Image/proceed.png");
var isFocused;

const PreviewMedia = ({ navigation, route }) => {
  const { uri, DocumentImageName, OnRetry, OnProceed } = route.params;

  const [retakeVisible, setRetakeVisible] = useState(false);
  const [isLoading, setIsLoading] = useState(false);

  /*@RCBPREVIEW*/
  const dispatch = useDispatch();
  isFocused = useIsFocused();

  useEffect(() => {
    UELogEvent("PreviewMedia, useEffect. URI, DocumentImageName", {
      URI: JSON.stringify(uri),
      DocumentImageName: JSON.stringify(DocumentImageName),
    });
    let Immersive = undefined;
    let restoreImmersive = undefined;
    if (!iOS) {
      Immersive = require("react-native-immersive").Immersive;
      Immersive.setImmersive(true);
      restoreImmersive = () => {
        __DEV__ && console.log("Immersive state changed!");
        Immersive.setImmersive(true);
      };
      Immersive.addImmersiveListener(restoreImmersive);
    }

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

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

    return () => {
      if (Immersive !== undefined) {
        Immersive.off();
        Immersive.removeImmersiveListener(restoreImmersive);
      }
      backHandler.remove();
      unsubscribe();
    };
  }, []);

  // const genrateActivityId=async()=>{
  //   try {
  //     setIsLoading(true)
  //     var vechicleData = await Database.get("PIVechicleData");
  //   CreateActivityId(async()=>{
  //     var registrationNumber = vechicleData?.licensePlateNumber
  //     var quoteNumber = vechicleData?.quoteNumber
  //     var activityTypeId = vechicleData?.activityTypeId
  //     var activityId = vechicleData?.activityId
  //     var toTutorial = vechicleData?.toTutorial
  //     var toWithQuote = vechicleData?.toWithQuote

  //     dispatch({
  //       type: "ACTIVITY_DATA",
  //       payload: {
  //         activityId: activityId,
  //         activityTypeId:activityTypeId,
  //         licensePlateNumber:
  //           registrationNumber === undefined ? "" : registrationNumber,
  //         toWithQuote: toWithQuote,
  //         toTutorial: toTutorial,
  //         quoteNumber: quoteNumber,
  //       },
  //     });
  //   },
  // (sensorImageDetails)=>{
  //   dispatch({
  //     type: "SENSOR_DETAILS",
  //     payload: sensorImageDetails,
  //   });
  // }
  //   )
  //   setIsLoading(false)

  //   } catch (error) {
  //     console.log("Error in RCBPreviewScreen.js CreateActivityId()",error);
  //     setIsLoading(false)
  //   }
  //  }

  const handleRetakeModalVisibility = () => {
    setRetakeVisible(!retakeVisible);
  };

  const handleRetry = () => {
    if (OnRetry !== undefined) {
      // Reset the pop instruction redux data
      dispatch({
        type: "RESET_POP_INSTRUCTION",
      });
      OnRetry(uri, DocumentImageName);
      navigation.pop();
    }
  };

  const retakeModal = () => {
    return (
      <View style={styles.RMContainer}>
        <View style={styles.RMMain}>
          <View style={{ flex: 0.05 }}>
            <Icon
              name="close"
              size={24}
              color={Colors.veryLightGray}
              style={{ alignSelf: "flex-end" }}
              onPress={handleRetakeModalVisibility}
            />
          </View>
          <View style={{ flex: 0.5 }}>
            <Text style={[style.muliBoldDB, styles.RMTitle]}>
              Do you want to retake ?
            </Text>
            <Text style={[style.muliRegDB, styles.RMSubtitle]}>
              Your current video recording will be discarded if you choose to
              retake.
            </Text>
          </View>
          <View style={styles.RMAction}>
            <PrimaryButton
              style={{ flex: 0.48 }}
              onPress={handleRetakeModalVisibility}
            >
              No, Don't Retake
            </PrimaryButton>
            <PrimaryButton
              onPress={handleRetry}
              mode={"outlined"}
              style={styles.RMDiscardButton}
            >
              Yes, Discard Video
            </PrimaryButton>
          </View>
        </View>
      </View>
    );
  };

  return (
    <SafeAreaView
      edges={iOS ? ["top", "bottom", "right"] : []}
      style={styles.safeArea}
    >
      <View style={styles.main}>
        {DocumentImageName == "VDO" && (
          <View style={{ position: "absolute", top: 10, zIndex: 2 }}>
            <Text style={[style.muliBoldDB, { color: "white", fontSize: 16 }]}>
              Preview Recording
            </Text>
          </View>
        )}
        <Spinner loading={isLoading} />
        <StatusBar hidden={true} />
        {/* Image View */}
        <View style={styles.imageView}>
          {/* Image */}
          {DocumentImageName == "VDO" ? (
            <VideoPlayer
              video={{ uri: uri }}
              pauseOnPress={true}
              autoplay={true}
              disableSeek={false}
            />
          ) : (
            <View>
              <Image source={{ uri: uri }} style={styles.imageStyle} />
            </View>
          )}
        </View>
        {/* Button View */}
        <View style={styles.buttonView}>
          {/* Retake View */}
          <View style={styles.retakeView}>
            <TouchableOpacity
              onPress={() => {
                if (DocumentImageName === "VDO") {
                  handleRetakeModalVisibility();
                } else {
                  handleRetry();
                }
              }}
            >
              <Image
                source={retake}
                style={{ width: 18, height: 18, alignSelf: "center" }}
              />
              <Text style={styles.retakeText}>{"Retake"}</Text>
            </TouchableOpacity>
          </View>
          {/* Proceed View */}
          <View style={styles.proceedView}>
            <TouchableOpacity
              onPress={() => {
                /* @RCBPREVIEW */
                if (DocumentImageName.includes("RCB")) {
                  let info = `RC ${
                    DocumentImageName === "RCB1" ? "Front" : "Back"
                  } Page`;

                  if (DocumentImageName !== "RCB1") {
                    if (DocumentImageName !== "RCB2") {
                      info = `RC More Pages`;
                    }
                  }

                  console.log(
                    "^^^PreviewMedia DocumentImageName",
                    DocumentImageName
                  );

                  dispatch({
                    type: "ADD_RCB_IMAGE",
                    payload: {
                      name: DocumentImageName,
                      image: uri,
                      info: info,
                    },
                  });
                }
                /* @RCBPREVIEW */
                if (OnProceed !== undefined) {
                  OnProceed(uri, DocumentImageName);
                  /* @RCBPREVIEW */
                  if (DocumentImageName.includes("RCB")) {
                    navigation.navigate("RCBPreviewScreen");
                  } else {
                    // navigation.pop()
                    navigation.navigate("Odometer");
                  }
                }
              }}
            >
              <Image
                source={proceed}
                style={{ width: 49, height: 49, alignSelf: "center" }}
              />
              <Text style={styles.retakeText}>{"Proceed"}</Text>
            </TouchableOpacity>
          </View>
          {/* Blank View */}
          <View style={styles.blankView} />
        </View>
      </View>
      {retakeVisible && retakeModal()}
    </SafeAreaView>
  );
};
export default PreviewMedia;

const styles = StyleSheet.create({
  safeArea: {
    flex: 1,
    backgroundColor: Colors.darkBlack,
  },
  main: {
    flex: 1,
    flexDirection: "row",
  },
  buttonView: {
    flex: 0.1,
    backgroundColor: "#000000",
  },
  imageView: {
    flex: 0.9,
    alignSelf: "center",
  },
  retakeView: {
    flex: 0.333333,
    justifyContent: "center",
  },
  proceedView: {
    flex: 0.333333,
    justifyContent: "center",
  },
  blankView: {
    flex: 0.3333333,
  },
  retakeText: {
    fontFamily: "Muli-Regular",
    fontSize: 11,
    alignSelf: "center",
    marginTop: 5,
    color: "#FFFFFF",
  },
  infoTextView: {
    // flex:0.1,
    position: "absolute",
    width: SCREEN_HEIGHT,
    height: 48,
    backgroundColor: "#000000",
    opacity: 0.58,
    justifyContent: "center",
  },
  infoText: {
    fontFamily: "Muli-SemiBold",
    fontSize: 14,
    color: "#FFFFFF",
    marginLeft: 24,
    marginRight: 24,
  },
  imageStyle: {
    width: "100%",
    height: "100%",
    resizeMode: "contain",
    alignSelf: "center",
  },
  RMContainer: {
    backgroundColor: "rgba(0,0,0,0.7)",
    position: "absolute",
    width: "100%",
    height: "100%",
    alignItems: "center",
    justifyContent: "center",
  },
  RMMain: {
    borderRadius: 8,
    backgroundColor: "white",
    height: "60%",
    width: "70%",
    padding: 16,
  },
  RMAction: {
    flex: 0.4,
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "flex-end",
  },
  RMTitle: {
    fontSize: 18,
    fontWeight: "700",
  },
  RMSubtitle: {
    fontSize: 14,
    fontWeight: "400",
    marginTop: 16,
  },
  RMDiscardButton: {
    flex: 0.48,
    borderColor: "#EE0000",
  },
});
