import React, { useEffect, useMemo, useRef, useState } from "react";
import {
  BackHandler,
  SafeAreaView,
  StatusBar,
  StyleSheet,
  View,
  TouchableOpacity,
  Alert,
  Text,
  Platform,
  Animated,
  Image,
  useColorScheme,
} from "react-native";
const iOS = Platform.OS === "ios";
import { Spinner } from "react-native-digitcamera/src/common/ThemedComponents";
import Colors from "react-native-digitcamera/src/common/Colors";
import MCIcon from "react-native-vector-icons/MaterialCommunityIcons";
import Database from "../../../../Components/common/DAsyncStorage";
import NetInfo from "@react-native-community/netinfo";
import { useIsFocused } from "@react-navigation/native";

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";
import { checkInternetSpeed } from "react-native-digitcamera/src/Screens/OfflineFlow/CommonFunc";
import { CreateActivityId } from "react-native-digitcamera/src/Screens/OfflineFlow/CreateActivityId";
import { useDispatch, useSelector } from "react-redux";
import Orientation from "react-native-orientation";
import style from "react-native-digitcamera/src/common/CommonStyle";
import { demopayd, demopi } from "../common/Assets";
const fast_backward = require("../common/Image/fast_backward.png");

const VideoControlButton = ({ imageSource, onPress }) => {
  return (
    <TouchableOpacity onPress={onPress} style={{ height: 24, width: 24 }}>
      <Image
        style={{
          height: 22,
          width: 18,
          // aspectRatio: 2,
        }}
        source={imageSource}
      />
    </TouchableOpacity>
  );
};

var isFocused;

const loadVideoSource = (videoUrl, internetAvailable, setVideoSource) => {
  if (internetAvailable) {
    setVideoSource({ uri: videoUrl, cache: true });
  } else {
    const videoUrlLowercase = videoUrl.toLowerCase();
    if (videoUrlLowercase.includes("payd")) {
      setVideoSource(demopayd);
    } else if (
      videoUrlLowercase.includes("pi") ||
      videoUrlLowercase.includes("preinspection")
    ) {
      setVideoSource(demopi);
    }
  }
};

const DemoVideo = ({ navigation, route }) => {
  /* 
  Animating this screen to make the navigation animation more smooth
   */
  const animatedOpacity = useRef(new Animated.Value(1)).current;

  const fadeInAnimation = Animated.timing(animatedOpacity, {
    toValue: 1,
    duration: 500,
    useNativeDriver: true,
  });

  // useEffect(() => {
  //   setTimeout(() => {
  //     fadeInAnimation.start();
  //   }, 200);
  // }, []);

  const { videoUri, OnSkip, OnProceed, withoutRCB } = route.params;
  const [actionVisibility, setActionVisibility] = useState(true);
  const [showSkipOption, setShowSkipOption] = useState(false);
  const [startInspection, setStartInspection] = useState(false);
  const [isNetworkAvailable, setIsNetworkAvailable] = useState(true);
  const [isBuffering, setIsBuffering] = useState(false);
  const [currentTime, setCurrentTime] = useState(0);
  const [videoSource, setVideoSource] = useState("NOT_AVAILABLE");

  var videoRef = useRef();
  const dispatch = useDispatch();
  isFocused = useIsFocused();

  const shouldEnableProceed = useRef(false);

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

  useEffect(() => {
    Orientation.lockToLandscapeLeft();
    checkForSkip();
    loadVideoSource(videoUri, isInternetReachable, setVideoSource);
    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);
    }

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

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

  const startInspectionView = () => {
    return (
      <View style={styles.startRecordingView}>
        {console.log("@@@@@@@@@", startInspection)}
        <View style={styles.startRecordingSubView}>
          <Text style={styles.textTitle}>{"You're ready!"}</Text>
          <View
            style={{ flexDirection: "row", justifyContent: "space-evenly" }}
          >
            <PrimaryButton
              onPress={() => {
                setStartInspection(false);
                setActionVisibility(false);
                if (videoRef) {
                  videoRef.current && videoRef.current.resume();
                }
              }}
              mode={"outlined"}
            >
              Replay Demo
            </PrimaryButton>
            <PrimaryButton
              style={styles.startRecordingButton}
              onPress={() => {
                navigation.navigate("QuickTips");
              }}
            >
              {"Let’s start"}
            </PrimaryButton>
          </View>
        </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 (
      __DEV__ ||
      (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");
    }
  };

  const onVideoStart = () => {
    // Let user spend 30 sec in Demo Video Screen
    setTimeout(() => {
      shouldEnableProceed.current = true;
    }, 30000);
  };

  const onFastBackward = () => {
    //get current time
    //and subtract 10sec
    if (typeof currentTime === "number" && currentTime > 10.0) {
      const seekTime = currentTime - 10.0;
      videoRef.current && videoRef.current.seek(seekTime);
    }
  };

  //not being used right know,
  //can be enabled later if required
  const onFastFarword = () => {
    //fast farword 10 sec
    videoRef.current && videoRef.current.seek(10);
  };

  const onProgress = (progress) => {
    const { currentTime } = progress;
    setCurrentTime(currentTime);
  };

  // const isDarkMode = useColorScheme() === "dark";
  const isDarkMode = false;

  return (
    <SafeAreaView
      edges={iOS ? ["top", "bottom", "right"] : []}
      style={styles.safeArea}
    >
      <Animated.View
        style={[
          styles.main,
          {
            opacity: animatedOpacity,
          },
        ]}
      >
        <Spinner loading={isBuffering} />
        <StatusBar
          barStyle={isDarkMode ? "light-content" : "dark-content"}
          hidden={true}
        />
        {videoSource === "NOT_AVAILABLE" ? (
          <View>
            <Text>Loading Video...</Text>
          </View>
        ) : (
          <VideoPlayer
            ref={videoRef}
            video={videoSource}
            videoHeight={480}
            videoWidth={640}
            playInBackground={false}
            pauseOnPress={true}
            autoplay={true}
            onProgress={onProgress}
            onLoad={() => {
              const timer = setTimeout(() => {
                clearTimeout(timer);
                if (videoRef) {
                  videoRef.current.pause();
                }
              }, 0);
            }}
            disableSeek={true}
            style={styles.productImageStyle}
            onEnd={() => {
              const update = async () => {
                await Database.update("PIDemoVideoViewStaus", {
                  isVideoSeen: true,
                });
              };
              update();
              if (shouldEnableProceed.current) {
                setStartInspection(true);
              }
              // check for skip option
              checkForSkip();
            }}
            customStyles={{
              seekBarProgress: {
                backgroundColor: Colors.digitYellow,
              },
              seekBarBackground: {
                backgroundColor: "#5F5B5B",
              },
            }}
          />
        )}
        <View
          style={{
            position: "absolute",
            bottom: 0,
            right: 0,
            left: 0,
            backgroundColor: "rgba(0,0,0,0.75)",
            padding: 6,
            justifyContent: "space-between",
            alignItems: "flex-end",
            flexDirection: "row",
            marginHorizontal: 10,
          }}
        >
          <View>
            <VideoControlButton
              imageSource={fast_backward}
              onPress={onFastBackward}
            />
          </View>
          <TouchableOpacity
            style={{}}
            onPress={() => {
              /* @STARTRECORDING */
              if (showSkipOption) {
                setStartInspection(true);
              }
            }}
          >
            {showSkipOption ? (
              <Text
                style={[style.muliboldBB, { color: "white", paddingRight: 8 }]}
              >
                {"Skip >>"}
              </Text>
            ) : (
              <Text
                style={[style.muliboldBB, { color: "white", paddingRight: 8 }]}
              >
                {"Please watch full video to proceed"}
              </Text>
            )}
          </TouchableOpacity>
        </View>

        {/* demo playing screen */}
        {false && (
          <View style={[styles.skipView]}>
            <TouchableOpacity
              style={{
                // flex: 1,
                flexDirection: "row",
                justifyContent: "space-between",
              }}
              onPress={() => {
                if (Platform.OS === "android") {
                  navigation.navigate("WithQuote");
                  // if (withoutRCB) {

                  //   Orientation.lockToPortrait();
                  // } else if (navigation.canGoBack()) {
                  //   navigation.pop();
                  // }
                }
              }}
            >
              <MCIcon
                name="arrow-bottom-left"
                size={24}
                color="white"
                style={{ transform: [{ rotate: "45deg" }], marginRight: 8 }}
              />
              <Text style={styles.demoVideoText}>{""}</Text>
            </TouchableOpacity>
            <TouchableOpacity
              style={{}}
              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") {
                  navigation.navigate("WithQuote");
                }
              }}
            >
              <MCIcon
                name="arrow-bottom-left"
                size={24}
                color="black"
                style={{ transform: [{ rotate: "45deg" }], marginTop: 4 }}
              />
            </TouchableOpacity>
            <TouchableOpacity
              style={{ justifyContent: "center", alignItems: "center" }}
              onPress={() => {
                setActionVisibility(false);
                if (videoRef) {
                  // setIsBuffering(true);
                  videoRef.current && videoRef.current.resume();
                  // start the timer
                  onVideoStart();
                }
              }}
            >
              <MCIcon
                name="play-circle"
                size={48}
                color={Colors.digitYellow}
                style={{ backgroundColor: "transparent" }}
              />
              <Text style={styles.playVideoText}>{"Watch Demo Video"}</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()}
      </Animated.View>
    </SafeAreaView>
  );
};
const styles = StyleSheet.create({
  safeArea: {
    flex: 1,
    backgroundColor: Colors.darkBlack,
  },
  main: {
    flex: 1,
    justifyContent: "flex-start",
  },
  productImageStyle: {
    height: "96%",
    width: "100%",
  },
  skipView: {
    position: "absolute",
    width: "100%",
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    backgroundColor: "transparent",
    padding: 16,
  },
  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,
    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: "10%",
    justifyContent: "center",
  },
  startRecordingSubView: {
    width: "40%",
    height: "50%",
    alignSelf: "center",
    borderRadius: 10,
    justifyContent: "space-evenly",
    backgroundColor: "#FFFFFF",
    paddingHorizontal: 16,
    elevation: 4,
  },
  textTitle: {
    color: "#000000",
    fontSize: 18,
    fontFamily: "Muli-Regular",
    alignSelf: "center",
    // paddingBottom: 24,
  },
  // startRecordingButton: {
  //   width: "70%",
  //   height: "10%",
  //   alignSelf: "center",
  // },
});
export default DemoVideo;
