import React, { useEffect, useRef, useState } from "react";
import {
  BackHandler,
  SafeAreaView,
  StatusBar,
  StyleSheet,
  View,
  TouchableOpacity,
  Alert,
  Text,
  Platform,
} from "react-native";
const iOS = Platform.OS === "ios";
import Orientation from "react-native-orientation";
import { Spinner } from "react-native-digitcamera/src/common/ThemedComponents";
import Colors from "react-native-digitcamera/src/common/Colors";
import Icon from "react-native-vector-icons/MaterialCommunityIcons";
import Database from "../../../../Components/common/DAsyncStorage";

import {
  SCREEN_HEIGHT,
  SCREEN_WIDTH,
} from "react-native-digitcamera/src/common/Constants";
import VideoPlayer from "react-native-video-player";
import { PrimaryButton } from "../../../../Components/common/ThemedComponents";
import {
  UELogEvent,
  UELogMessage,
} from "../common/libEventLog/UserExperior/LibUserExperior";

const DemoVideo = ({ navigation, route }) => {
  const { videoUri, OnSkip, OnProceed, onSkipToVideoPI } = route.params;
  const [actionVisibility, setActionVisibility] = useState(true);
  const [showSkipOption, setShowSkipOption] = useState(false);
  const [startInspection, setStartInspection] = useState(false);
  var videoRef = useRef();

  useEffect(() => {
    // check for skip option
    // UELogEvent("DemoVideo useEffect, videoUri:", {
    //   "videoURI": JSON.stringify(videoUri)
    // })
    checkForSkip();

    console.log("**** DemoVideo useEffect: videoUri: " + videoUri);
    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 startInspectionView = () => {
    return (
      <View style={styles.startRecordingView}>
        {console.log("@@@@@@@@@", startInspection)}
        <View style={styles.startRecordingSubView}>
          <Text style={styles.textTitle}>{"You're ready!"}</Text>
          <PrimaryButton
            style={styles.startRecordingButton}
            onPress={() => {
              if (OnProceed) {
                OnProceed();
              }
            }}
          >
            {"Start Inspection"}
          </PrimaryButton>
        </View>
      </View>
    );
  };

  const checkForSkip = async () => {
    var PIDemoVideoViewStaus = await Database.get("PIDemoVideoViewStaus");
    var AppLoginStatus = await Database.get("AppLoginStatus");

    console.log(
      "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!",
      PIDemoVideoViewStaus?.isVideoSeen,
      AppLoginStatus.userType
    );
    UELogEvent("DemoVideo, checkForSkip", {
      PIDemoVideoViewStatus: JSON.stringify(PIDemoVideoViewStaus?.isVideoSeen),
      AppLoginStatus: JSON.stringify(AppLoginStatus?.userType),
    });
    if (
      PIDemoVideoViewStaus?.isVideoSeen == true &&
      AppLoginStatus.userType === "DealerOrAgent"
    ) {
      // show skip
      setShowSkipOption(true);
      console.log("*** DemoVideo skip option shown");
    } else if (PIDemoVideoViewStaus?.isVideoSeen == undefined) {
      setShowSkipOption(false);
      console.log("*** DemoVideo skip option removed");
    }
  };
  return (
    <SafeAreaView
      edges={iOS ? ["top", "bottom", "right"] : []}
      style={styles.safeArea}
    >
      <View style={styles.main}>
        <Spinner loading={false} />
        <StatusBar hidden={true} />
        <VideoPlayer
          ref={(p) => (videoRef = p)}
          video={{ uri: videoUri, cache: true }}
          videoHeight={SCREEN_HEIGHT}
          videoWidth={SCREEN_WIDTH}
          playInBackground={false}
          pauseOnPress={true}
          autoplay={true}
          onLoad={() => {
            const timer = setTimeout(() => {
              clearTimeout(timer);
              if (videoRef) {
                videoRef.pause();
              }
            }, 2000);
          }}
          disableSeek={true}
          style={styles.productImageStyle}
          onEnd={() => {
            update = async () => {
              await Database.update("PIDemoVideoViewStaus", {
                isVideoSeen: true,
              });
            };
            update();
            setStartInspection(true);
            // check for skip option
            checkForSkip();
          }}
        ></VideoPlayer>

        {/* demo playing screen */}
        {!actionVisibility && (
          <View style={[styles.skipView]}>
            <TouchableOpacity
              style={{
                justifyContent: "flex-start",
                alignItems: "center",
                flexDirection: "row",
              }}
              onPress={() => {
                if (Platform.OS === "android") {
                  if (navigation.canGoBack()) {
                    navigation.pop();
                  }
                }
              }}
            >
              <Icon
                name="arrow-left"
                size={48}
                color={"white"}
                style={{ backgroundColor: "transparent" }}
              />
              <Text style={styles.demoVideoText}>
                {"Watch a quick Pre-Inspection guide"}
              </Text>
            </TouchableOpacity>
            <TouchableOpacity
              style={{ justifyContent: "center", alignItems: "center" }}
              onPress={() => {
                /* @STARTRECORDING */
                if (showSkipOption) {
                  setStartInspection(true);
                }
              }}
            >
              {showSkipOption ? (
                <Text style={styles.proceedText}>{"Skip >>"}</Text>
              ) : (
                <Text style={styles.proceedText}>
                  {"Please watch full video to proceed"}
                </Text>
              )}
            </TouchableOpacity>
          </View>
        )}

        {/* pop-up screen */}
        {actionVisibility && (
          <View style={[styles.payView]}>
            <TouchableOpacity
              style={{
                justifyContent: "flex-start",
                alignItems: "center",
                flexDirection: "row",
                position: "absolute",
                left: 1,
                top: 1,
                padding: 16,
              }}
              onPress={() => {
                if (Platform.OS === "android") {
                  // if (navigation.canGoBack()) {
                  //   navigation.pop();
                  // }
                  /* @NEWORDER */
                  navigation.navigate("Toturial", { fromRCB: true });
                }
              }}
            >
              <Icon
                name="arrow-left"
                size={48}
                color={"white"}
                style={{ backgroundColor: "transparent" }}
              />
            </TouchableOpacity>
            <TouchableOpacity
              style={{ justifyContent: "center", alignItems: "center" }}
              onPress={() => {
                setActionVisibility(false);
                if (videoRef) {
                  videoRef.resume();
                }
              }}
            >
              <Icon
                name="play-circle"
                size={48}
                color={Colors.digitYellow}
                style={{ backgroundColor: "transparent" }}
              />
              <Text style={styles.playVideoText}>
                {"Watch a quick Pre-Inspection guide"}
              </Text>
              <Text style={styles.infoText}>
                {"Please watch full video to proceed"}
              </Text>
            </TouchableOpacity>

            {/* Skip button on paused screen */}
            <TouchableOpacity
              style={{ position: "absolute", right: 1, bottom: 1, padding: 18 }}
              onPress={() => {
                if (showSkipOption) {
                  setStartInspection(true);
                }
              }}
            >
              {showSkipOption ? (
                <Text style={styles.proceedText}>{"Skip >>"}</Text>
              ) : null}
            </TouchableOpacity>
          </View>
        )}
        {startInspection && startInspectionView()}
      </View>
    </SafeAreaView>
  );
};
const styles = StyleSheet.create({
  safeArea: {
    flex: 1,
    backgroundColor: Colors.darkBlack,
  },
  main: {
    flex: 1,
    justifyContent: "flex-start",
  },
  productImageStyle: {
    height: "100%",
    width: "100%",
  },
  skipView: {
    position: "absolute",
    width: "100%",
    flexDirection: "column",
    height: "87%",
    justifyContent: "space-between",
    backgroundColor: "transparent",
  },
  payView: {
    position: "absolute",
    width: "100%",
    flexDirection: "column",
    height: "100%",
    justifyContent: "center",
    backgroundColor: "rgba(0, 0, 0, 0.8)",
  },
  demoVideoText: {
    backgroundColor: "transparent",
    fontFamily: "Muli-Bold",
    fontSize: 18,
    padding: 20,
    alignSelf: "flex-start",
    color: "white",
  },
  playVideoText: {
    backgroundColor: "transparent",
    fontFamily: "Muli-Bold",
    fontSize: 18,
    padding: 20,
    alignSelf: "center",
    color: "white",
  },
  proceedText: {
    backgroundColor: "transparent",
    fontFamily: "Muli-Regular",
    fontSize: 13,
    alignSelf: "flex-end",
    color: "white",
    paddingRight: 23,
  },
  infoText: {
    backgroundColor: "transparent",
    fontFamily: "Muli-Regular",
    fontSize: 13,
    alignSelf: "center",
    color: "white",
  },
  startRecordingView: {
    position: "absolute",
    zIndex: 400,
    width: "100%",
    height: "80%",
    top: "20%",
    justifyContent: "center",
    backgroundColor: "transparent",
  },
  startRecordingSubView: {
    width: "50%",
    height: "50%",
    alignSelf: "center",
    borderRadius: 10,
    justifyContent: "center",
    backgroundColor: "#FFFFFF",
  },
  textTitle: {
    color: "#000000",
    fontSize: 18,
    fontFamily: "Muli-Regular",
    alignSelf: "center",
    paddingBottom: 24,
  },
  startRecordingButton: {
    width: "70%",
    height: "10%",
    alignSelf: "center",
  },
});
export default DemoVideo;
