import React, { useEffect, useState } from "react";
import {
  View,
  Text,
  Image,
  StyleSheet,
  Alert,
  ActivityIndicator,
  Dimensions,
  TouchableOpacity,
} from "react-native";
import style from "../../../../Components/common/CommonStyle";
import { PrimaryButton } from "react-native-digitcamera/src/common/ThemedComponents";
import Orientation from "../../../react-native-orientation";
import Database from "../../../../Components/common/DAsyncStorage";
import Colors from "react-native-digitcamera/src/common/Colors";
import Icon from "react-native-vector-icons/MaterialCommunityIcons";
import InIcon from "react-native-vector-icons/Ionicons";
import MIcon from "react-native-vector-icons/MaterialIcons";
import ImagePlaceholder from "../common/ImagePlaceholder";
import BoldText from "../common/BoldText";
import {
  play,
  digitPreAudios,
} from "react-native-digitcamera/src/common/DSound";
import { zIndex_close_bonnet } from "react-native-digitcamera/src/Screens/StencilAnimation";
import { ACTIVITY_TYPE_MOTOR_4W_OD_NB_PRE_INSPECTION_SELF_SURVEY } from "react-native-digitcamera/src/common/Constants";
import { useMemo } from "react";
import VideoPlayer from "react-native-video-player";
import NetInfo from "@react-native-community/netinfo";
const car_start = require("../common/Image/car_start.mp4");

/*
Import Modal from lib
add shouldHeaderVisible props
*/

/*
    Dimension issue fixed
*/

/* Get max dimension for screen width */

const getMinWidth = () => {
  return Math.round(
    Math.min(Dimensions.get("screen").height, Dimensions.get("screen").width)
  );
};
/*Initial SCREEN_WIDTH*/
let SCREEN_WIDTH = getMinWidth();

// var instructionInDb = Database.get("PIVechicleInstruction");

const DATA = [
  {
    surveyInstructionsId: 1742,
    instructionAssests:
      "https://d2h44aw7l5xdvz.cloudfront.net/CRM/PRM/open_bonnet.gif",
    instructionTitle: "Open the car bonnet",
    instructionData: "Before we get started, please open up the car bonnet",
    okButtonText: "I have opened the bonnet",
  },

  {
    surveyInstructionsId: 1743,
    instructionAssests:
      "https://d2h44aw7l5xdvz.cloudfront.net/CRM/PRM/key_start.png",
    instructionTitle: "Start your vehicle",
    instructionData:
      "The engine should be ON for taking the odomenter reading & while recording the video.",
    okButtonText: "I have started the vehicle",
  },
  {
    surveyInstructionsId: 1744,
    instructionAssests:
      "https://d2h44aw7l5xdvz.cloudfront.net/CRM/PRM/chassis_car.png",
    instructionTitle: "Find your chassis number",
    instructionData:
      "Locate your chassis number, you can refer to the image to find chassis number.",
    okButtonText: "I have found the chassis number",
  },
  {
    surveyInstructionsId: 1745,
    instructionAssests:
      "https://d2h44aw7l5xdvz.cloudfront.net/CRM/PRM/chassis_find.png",
    instructionTitle: "What is embossed chassis no.?",
    instructionData: "What is embossed chassis no.?",
  },
  {
    surveyInstructionsId: 1746,
    instructionAssests:
      "https://d2h44aw7l5xdvz.cloudfront.net/CRM/PRM/chassis_find.png",
    instructionTitle: "What is embossed chassis no.?",
    instructionData: "What is embossed chassis no.?",
  },
];

/* Sort instruction by display order */
const sortByDisplayOrder = (arr) => {
  const sortedArray = arr.sort(function (a, b) {
    return parseInt(a.displayOrder) - parseInt(b.displayOrder);
  });
  return sortedArray;
};
var playList = [];
const InstructionsScreen = (props) => {
  const [stepCount, setStepCount] = useState(0);
  const [instructionArr, setInstructionArr] = useState(
    JSON.parse(props.instruction)
  );
  const [data, setData] = useState();
  const [imageLoaded, setImageLoaded] = useState(false);
  const [stepsLength, setStepsLength] = useState(0);
  const [isNetworkAvailable, setIsNetworkAvailable] = useState(true);

  useEffect(() => {
    // if (Orientation.getInitialOrientation() === "PORTRAIT") {
    //     Orientation.lockToLandscape()
    // }

    var unsubscribeNetInfo = NetInfo.addEventListener(async (state) => {
      console.log("In NetInfo InstuctionScreen");
      if (state.isInternetReachable != null) {
        setIsNetworkAvailable(state.isInternetReachable);
      }
    });

    playList = [];
    Orientation.lockToLandscape();
    SCREEN_WIDTH = getMinWidth();

    // Comment this to enable local images
    let item = instructionArr.find((item) => item.imageName === "VDO");
    if (item !== undefined) {
      if (item?.TSurveyInstructions?.length !== 0) {
        const imageTypeInstructions = item?.TSurveyInstructions.filter(
          (item) =>
            (item?.type === "image" || item?.type === "video") &&
            item?.instructionTitle !== "Quick Tips"
        );
        const sortedInstructions = sortByDisplayOrder(imageTypeInstructions);
        // setData(item?.TSurveyInstructions);
        setData(sortedInstructions);
        console.log(
          "&&&&&&&&&&&&& sortedInstructions &&&&&&&&&&&&&",
          JSON.stringify(sortedInstructions)
        );
        // Close the bonnet modal
        if (props.shouldCloseTheBonnet) {
          const closeTheBonnetIndex = sortedInstructions?.findIndex(
            (item) => item.okButtonText === "Ready!"
          );
          if (closeTheBonnetIndex) {
            console.log("($) Close The Bonnet Index", closeTheBonnetIndex);
            setStepsLength(1);
            setStepCount(closeTheBonnetIndex);
          }
        }
        // First three instructions modal
        else {
          /*
           * Extracts Instructions other than, embossed & sticker chassis & Close The Bonnet instructions.
           *
           */
          const nonChassisInstrDataLength = sortedInstructions.filter(
            (item) =>
              item.hasOwnProperty("okButtonText") &&
              !(item.okButtonText === "Ready!")
          );
          const totalStepsLength = nonChassisInstrDataLength.length;
          console.log(
            "($) InstructionsScreen sortedInstructions Length ->",
            totalStepsLength
          );
          setStepsLength(totalStepsLength);
        }
      }
    }
    return () => {
      unsubscribeNetInfo && unsubscribeNetInfo();
    };
  }, []);

  const playAudioMemo = useMemo(() => {
    const playAudio = async () => {
      const vehicleDetails = await Database.get("PIVechicleData");
      const activtyTypeId = vehicleDetails?.activityTypeId;
      if (
        activtyTypeId &&
        activtyTypeId == ACTIVITY_TYPE_MOTOR_4W_OD_NB_PRE_INSPECTION_SELF_SURVEY
      ) {
        const startCarPlayer = play(digitPreAudios["start_car"]);
        playList.push(startCarPlayer);
      } else {
        const bonnerPlayer = play(digitPreAudios["bonnet"]);
        playList.push(bonnerPlayer);
      }
    };
    if (!props.shouldCloseTheBonnet) playAudio();
  }, [instructionArr]);

  const stopPreviousIfAny = () => {
    playList.map((item) => {
      item?.(); // stop
    });
    playList = [];
  };

  const playSound = async (soundName) => {
    console.log("($) playSound -> ", soundName);
    const okButtonText = soundName;
    console.log("($) Instruction okButtonText: ", okButtonText);
    if (okButtonText && okButtonText.includes("bonnet")) {
      stopPreviousIfAny();
      const bonnetPlayer = play(digitPreAudios["bonnet"]);
      playList.push(bonnetPlayer);
    } else if (okButtonText && okButtonText.includes("started")) {
      const vehicleDetails = await Database.get("PIVechicleData");
      const activtyTypeId = vehicleDetails?.activityTypeId;
      if (
        activtyTypeId &&
        activtyTypeId == ACTIVITY_TYPE_MOTOR_4W_OD_NB_PRE_INSPECTION_SELF_SURVEY
      ) {
        props.startRecording();
      } else {
        stopPreviousIfAny();
        const startCarPlayer = play(digitPreAudios["start_car"]);
        playList.push(startCarPlayer);
      }
    } else if (okButtonText && okButtonText.includes("chassis")) {
      stopPreviousIfAny();
      const chassisPlayer = play(digitPreAudios["chassis"]);
      playList.push(chassisPlayer);
    }
  };

  const handleButtonPress = () => {
    // Close the bonnet callback
    if (props.shouldCloseTheBonnet) {
      if (props.onCloseCallback) {
        playSound(getSoundName(stepCount));
        props.onCloseCallback();
      }
    }
    /*
        stepCount refers to the number of steps 
        intialized as 0 for to act as index for 
        intstructions array.
        */
    console.log("*** InstructionsScreen stepCount: " + stepCount);
    if (stepCount < stepsLength - 1) {
      //this condition is for when there is an video the audio will play after complete the video
      if (data[stepCount + 1]?.type != "video") {
        playSound(getSoundName(stepCount + 1));
      }
      /*
            Loads next instructions
            */
      setStepCount(stepCount + 1);
      setImageLoaded(false);
    } else {
      /*
            startRecording callback
            */
      stopPreviousIfAny();
      props.startRecording();
    }
  };

  const handleStepBack = () => {
    if (stepCount > 0) {
      //this condition is for when there is an video the audio will play after complete the video
      if (data[stepCount - 1]?.type != "video") {
        playSound(getSoundName(stepCount - 1));
      }
      setStepCount(stepCount - 1);
    }
  };

  const handleEmbossisModalBack = () => {
    const embossInstrIndex = data?.findIndex((item) =>
      item.okButtonText.includes("chassis")
    );
    setStepCount(embossInstrIndex);
  };

  const handleStepForward = () => {
    if (stepCount < stepsLength - 1) {
      //this condition is for when there is an video the audio will play after complete the video
      if (data[stepCount + 1]?.type != "video") {
        playSound(getSoundName(stepCount + 1));
      }
      setStepCount(stepCount + 1);
    }
  };

  const handleOnInfoPress = () => {
    setStepCount(stepsLength);
  };

  const shouldGoToEmbossedChassisInstr = () => {
    const searchText = "Find your chassis number".trim();
    if (data?.find((item) => item?.instructionTitle === searchText)) {
      if (
        data?.findIndex((item) => item?.instructionTitle === searchText) ===
        stepCount
      ) {
        return true;
      }
    }
    return false;
  };

  const getSoundName = (stepIndex) => {
    const soundString =
      data !== undefined
        ? data[stepIndex]?.okButtonText
        : DATA[stepIndex]?.okButtonText;
    console.log("($) getSoundName -> ", soundString);
    return soundString;
  };

  const embossedChassisInfoModal = () => {
    return (
      <View
        style={{
          height: SCREEN_WIDTH * 0.8,
          padding: 16,
          paddingTop: 8,
          justifyContent: "space-between",
        }}
      >
        {
          <View
            style={{
              flex: 0.1,
              flexDirection: "row",
              alignItems: "center",
              justifyContent: "flex-start",
            }}
          >
            <TouchableOpacity
              style={{ backgroundColor: "#F5F5F5", borderRadius: 25 }}
              onPress={handleEmbossisModalBack}
            >
              <MIcon
                name="arrow-back"
                size={18}
                color={"#999999"}
                // onPress={handleStepBack}
              />
            </TouchableOpacity>
            <Text style={[style.muliBoldDB, { fontSize: 14, marginLeft: 10 }]}>
              {data !== undefined
                ? data[stepCount]?.instructionData
                : DATA[stepCount]?.instructionData}
            </Text>
          </View>
        }
        <View
          style={{
            flex: 0.85,
            flexDirection: "row",
            justifyContent: "space-between",
          }}
        >
          <View style={{ flex: 0.49 }}>
            <View style={{ position: "absolute", zIndex: 1, right: 0 }}>
              <View style={[styles.iSIconView, { backgroundColor: "#00AA55" }]}>
                <InIcon name="checkmark-sharp" size={24} color={"white"} />
              </View>
            </View>
            <Image
              key={
                data !== undefined
                  ? data[stepCount]?.surveyInstructionsId
                  : DATA[stepCount]?.surveyInstructionsId
              }
              source={{
                uri:
                  data !== undefined
                    ? data[stepCount]?.instructionAssests
                    : DATA[stepCount]?.instructionAssests,
                cache: "only-if-cached",
              }}
              // source={{ uri: props.instructionAssests === undefined ? data[stepCount].instructionAssests : props.instructionAssests }}
              style={styles.iSImage}
              onLoadEnd={() => {
                console.log("Image got loaded");
              }}
              onLoadStart={() => setImageLoaded(false)}
            />
            <View style={styles.iSFetchingImageIndicator}>
              {/* <ImagePlaceholder /> */}
            </View>
          </View>
          <View style={{ flex: 0.49 }}>
            <View style={{ position: "absolute", zIndex: 1, right: 0 }}>
              <View style={[styles.iSIconView, { backgroundColor: "#EE0000" }]}>
                <InIcon name="close-sharp" size={24} color={"white"} />
              </View>
            </View>
            <Image
              source={{
                // uri:
                //   "https://d2h44aw7l5xdvz.cloudfront.net/CRM/PRM/chassis_find.png",
                uri:
                  data !== undefined
                    ? data[stepCount + 1].instructionAssests
                    : DATA[stepCount + 1].instructionAssests,
                cache: "only-if-cached",
              }}
              style={{
                height: "100%",
                width: "100%",
                resizeMode: "contain",
              }}
            />
            <View style={styles.iSFetchingImageIndicator}>
              {/* <ImagePlaceholder /> */}
            </View>
          </View>
        </View>
      </View>
    );
  };

  const txt =
    data !== undefined
      ? data[stepCount]?.instructionData
      : DATA[stepCount]?.instructionData;

  return (
    <View style={styles.iSContainer}>
      {stepCount !== stepsLength && (
        <View
          style={[
            styles.iSInstructionsContainer,
            props.shouldCloseTheBonnet ? { height: SCREEN_WIDTH * 0.45 } : {},
          ]}
        >
          <View style={styles.iSImageContainer}>
            {/* Image Container */}
            <View style={styles.iSImageView}>
              {data[stepCount]?.type == "image" ? (
                <Image
                  key={
                    data !== undefined
                      ? data[stepCount]?.surveyInstructionsId
                      : DATA[stepCount]?.surveyInstructionsId
                  }
                  source={{
                    uri:
                      // "https://d2h44aw7l5xdvz.cloudfront.net/CRM/PRM/chassis_find.png",
                      data !== undefined
                        ? data[stepCount]?.instructionAssests
                        : DATA[stepCount]?.instructionAssests,
                    cache: "only-if-cached",
                  }}
                  // source={{ uri: props.instructionAssests === undefined ? data[stepCount].instructionAssests : props.instructionAssests }}
                  style={[
                    styles.iSImage,
                    props.shouldCloseTheBonnet ? { resizeMode: "contain" } : {},
                  ]}
                  onLoadEnd={() => setImageLoaded(true)}
                  onLoadStart={() => setImageLoaded(false)}
                />
              ) : (
                <VideoPlayer
                  key={
                    data !== undefined
                      ? data[stepCount]?.surveyInstructionsId
                      : DATA[stepCount]?.surveyInstructionsId
                  }
                  video={car_start}
                  pauseOnPress={true}
                  autoplay={true}
                  disableSeek={true}
                  loop={true}
                  style={styles.iSVideo}
                  onEnd={() => {
                    playSound(getSoundName(stepCount)); // the Audio instuctions will play now
                  }}
                />
              )}
            </View>

            {/* Instructions Details & Action */}
            <View style={styles.iSInstructionsView}>
              {/* Instructions Steps,Title,Detailss */}
              <View style={styles.iSTitleDetailParent}>
                <View
                  style={[
                    styles.iSStepTitle,
                    props.shouldCloseTheBonnet ? { flex: 0.3 } : {},
                  ]}
                >
                  {!(stepsLength === 1) && (
                    <View style={styles.iSStepAction}>
                      <TouchableOpacity
                        hitSlop={{ top: 24, bottom: 24, right: 24, left: 24 }}
                        style={{
                          backgroundColor:
                            stepCount === 0 ? "transparent" : "#F5F5F5",
                          borderRadius: 25,
                        }}
                        onPress={handleStepBack}
                      >
                        <MIcon
                          name="arrow-back"
                          size={18}
                          color={stepCount === 0 ? "transparent" : "#999999"}
                        />
                      </TouchableOpacity>
                      <Text style={[styles.iSCurrentStep, style.muliRegLG]}>
                        Step{" "}
                        <Text>
                          {stepCount + 1}/{stepsLength}
                        </Text>
                      </Text>
                      <TouchableOpacity
                        hitSlop={{ top: 24, bottom: 24, right: 24, left: 24 }}
                        style={{
                          backgroundColor:
                            stepCount === stepsLength - 1
                              ? "transparent"
                              : "#F5F5F5",
                          borderRadius: 25,
                        }}
                        onPress={handleStepForward}
                      >
                        <MIcon
                          name="arrow-forward"
                          size={18}
                          color={
                            stepCount === stepsLength - 1
                              ? "transparent"
                              : "#999999"
                          }
                        />
                      </TouchableOpacity>
                    </View>
                  )}
                  <Text
                    style={[
                      style.muliBoldDB,
                      styles.iSTitle,
                      props.shouldCloseTheBonnet ? { marginVertical: 0 } : {},
                    ]}
                  >
                    {data !== undefined
                      ? data[stepCount]?.instructionTitle
                      : DATA[stepCount]?.instructionTitle}
                  </Text>
                </View>
                <View
                  style={[
                    styles.iSDetailsView,
                    {
                      flexDirection: "column",
                      justifyContent: "space-between",
                    },
                  ]}
                >
                  {txt &&
                    (props.shouldCloseTheBonnet ? (
                      txt
                        .split(",")
                        .map((item) => (
                          <BoldText
                            key={item}
                            style={[style.muliRegDB, styles.iSDetails]}
                            text={`\u2022 ${item.trim()}`}
                            boldTextColor={Colors.darkBlack}
                          />
                        ))
                    ) : (
                      <BoldText
                        style={[style.muliRegDB, styles.iSDetails]}
                        text={txt}
                        boldTextColor={Colors.darkBlack}
                      />
                    ))}

                  {/* <Text
                  style={[style.muliRegDB, styles.iSDetails]}
                  numberOfLines={6}
                > 
              </Text>*/}
                  <View>
                    {shouldGoToEmbossedChassisInstr() && (
                      <TouchableOpacity
                        style={{
                          backgroundColor: "#FFFAEB",
                          padding: 8,
                          flexDirection: "row",
                          alignItems: "center",
                          justifyContent: "space-between",
                        }}
                        onPress={handleOnInfoPress}
                      >
                        <Text style={[style.muliBoldDB]}>
                          What is embossed chassis no.?
                        </Text>
                        <View
                          style={{
                            borderRadius: 25,
                            borderWidth: 2,
                            borderColor: Colors.digitYellow,
                            height: 24,
                            width: 24,
                            alignItems: "center",
                            justifyContent: "center",
                          }}
                        >
                          <Text
                            style={[
                              style.muliBoldDB,
                              { color: Colors.borderBlack },
                            ]}
                          >
                            i
                          </Text>
                        </View>
                      </TouchableOpacity>
                    )}
                  </View>
                </View>
              </View>
              {/* Action Button */}
              <View style={styles.iSButtonView}>
                {console.log(
                  "data[stepCount]?.okButtonText",
                  data[stepCount]?.type
                )}
                <PrimaryButton onPress={handleButtonPress}>
                  {data !== undefined
                    ? data[stepCount]?.okButtonText
                    : DATA[stepCount]?.okButtonText}
                </PrimaryButton>
              </View>
            </View>
          </View>
        </View>
      )}
      {stepCount === stepsLength && embossedChassisInfoModal()}
    </View>
  );
};
// iS = Instruction Screen
const styles = StyleSheet.create({
  iSContainer: {
    // flex: 1,
    zIndex: zIndex_close_bonnet,
    width: "100%",
    justifyContent: "flex-end",
    // backgroundColor: "white",
  },
  iSInstructionsContainer: {
    padding: 16,
    paddingTop: 8,
    // borderTopLeftRadius: 10,
    // borderTopRightRadius: 10,
    // elevation: 5,
    height: SCREEN_WIDTH * 0.8,
    // backgroundColor: 'white'
  },
  iSImageContainer: {
    flex: 1,
    flexDirection: "row",
    justifyContent: "space-between",
  },
  iSImageView: {
    flex: 0.5,
  },
  iSImage: {
    height: "100%",
    width: "100%",
    borderRadius: 8,
    resizeMode: "stretch",
  },
  iSVideo: {
    height: "100%",
    width: "100%",
    borderRadius: 8,
  },
  iSInstructionsView: {
    flex: 0.45,
  },
  iSTitleDetailParent: {
    flex: 0.7,
  },
  iSStepTitle: {
    flex: 0.4,
  },
  iSStepAction: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "space-between",
  },
  iSCurrentStep: {
    fontSize: 13,
  },
  iSTitle: {
    fontSize: 18,
    marginVertical: 16,
  },
  iSDetailsView: {
    marginTop: 8,
    flex: 0.7,
    flexShrink: 1,
  },
  iSDetails: {
    fontSize: 14,
    flexShrink: 1,
    // textAlign: 'justify'
    marginHorizontal: 0 /* overrides the existing property in  BoldText*/,
  },
  iSButtonView: {
    flex: 0.3,
    justifyContent: "flex-end",
  },
  iSFetchingImageIndicator: {
    position: "absolute",
    top: 0,
    bottom: 0,
    right: 0,
    left: 0,
  },
  iSIconView: {
    width: 36,
    height: 36,
    borderRadius: 250,
    justifyContent: "center",
    alignItems: "center",
    marginRight: 4,
    marginTop: 4,
  },
});

export default InstructionsScreen;
