import React, { useEffect, useState, useRef } from "react";
import {
  View,
  Text,
  Image,
  StyleSheet,
  Alert,
  ActivityIndicator,
  Dimensions,
  TouchableOpacity,
  FlatList,
} from "react-native";
import style from "../../../../Components/common/CommonStyle";
import { PrimaryButton } from "react-native-digitcamera/src/common/ThemedComponents";
import Modal from "react-native-modal";
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 {
  openbonnet,
  chassis_car,
  embossedchassis,
  stickerchassis,
} from "../common/Assets";
import { useSelector } from "react-redux";

const getMaxDimension = () => {
  return Math.round(
    Math.max(Dimensions.get("screen").height, Dimensions.get("screen").width)
  );
};

let SCREEN_WIDTH = getMaxDimension();

const getImageByTitle = (title) => {
  switch (title) {
    case "Please open the bonnet of the car":
      return openbonnet;
    case "Start your car":
      return car_start;
    case "Find your chassis number":
      return chassis_car;
    case "Start your vehicle":
      return car_start;
  }
};

const generateInstructionData = (data, isInternetReachable) => {
  const modifiedData = data.map((item) => {
    if (isInternetReachable) {
      if (item.tInstructionMandate.length > 0) {
        const tInstructionMandateModified = item.tInstructionMandate.map(
          (mandateItem) => {
            return { ...mandateItem, link: { uri: item.link } };
          }
        );
        return {
          ...item,
          tInstructionMandate: tInstructionMandateModified,
          instructionAssests: { uri: item.instructionAssests },
        };
      } else {
        return {
          ...item,
          instructionAssests: { uri: item.instructionAssests },
        };
      }
    } else {
      if (item.tInstructionMandate.length > 0) {
        const tInstructionMandateModified = item.tInstructionMandate.map(
          (mandateItem, index) => {
            return {
              ...mandateItem,
              link: index === 0 ? embossedchassis : stickerchassis,
            };
          }
        );
        return {
          ...item,
          tInstructionMandate: tInstructionMandateModified,
          instructionAssests: item.instructionAssests,
        };
      } else {
        return {
          ...item,
          instructionAssests: getImageByTitle(item.instructionTitle),
        };
      }
    }
  });
  const filteredData = modifiedData.filter(
    (item) => item.instructionTitle !== "Make sure"
  );
  return filteredData;
};

/* 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 ChassisInstructView = ({
  instructionTitle,
  doImage,
  dontImage,
  onPrev,
}) => {
  return (
    <View key={instructionTitle} style={styles.chassisInstructViewParent}>
      <View style={styles.chassisInstructViewHeader}>
        <TouchableOpacity
          hitSlop={{ top: 24, bottom: 24, right: 24, left: 24 }}
          style={styles.backButtonIcon}
          onPress={onPrev}
        >
          <MIcon name="arrow-back" size={18} color={"#999999"} />
        </TouchableOpacity>

        <Text style={[style.muliBoldDB, styles.iSCurrentStep]}>
          {instructionTitle}
        </Text>
      </View>
      <View style={styles.chassisInstructViewFooter}>
        <View style={{ flex: 0.48 }}>
          <View style={[styles.iSIconView, styles.correctIconStyle]}>
            <InIcon name="checkmark-sharp" size={24} color={"white"} />
          </View>
          <Image
            source={embossedchassis}
            style={styles.imageDimension}
            resizeMode={"contain"}
            resizeMethod="scale"
          />
        </View>
        <View style={{ flex: 0.48 }}>
          <View style={[styles.iSIconView, styles.incorrectIconStyle]}>
            <InIcon name="close-sharp" size={24} color={"white"} />
          </View>
          <Image
            source={stickerchassis}
            style={styles.imageDimension}
            resizeMode={"contain"}
            resizeMethod="scale"
          />
        </View>
      </View>
    </View>
  );
};

const InstructView = ({
  instructionAssests,
  instructionData,
  instructionTitle,
  okButtonText,
  type,
  tInstructionMandate,
  index,
  totalSteps,
  onNext,
  onPrev,
  onProceed,
  playSound,
  getSoundName,
  videoPlayerRef,
}) => {
  const onPressCallback = () => {
    if (instructionTitle === "Find your chassis number") {
      onProceed();
    } else {
      onNext();
    }
  };

  if (instructionTitle === "What is embossed chassis no.?") {
    return (
      <ChassisInstructView
        instructionTitle={instructionTitle}
        doImage={tInstructionMandate[0]?.link}
        dontImage={tInstructionMandate[1]?.link}
        onPrev={onPrev}
      />
    );
  }
  return (
    <View key={index} style={styles.instructViewParent}>
      <View style={styles.instructViewLeft}>
        {type === "image" && instructionTitle !== "Start your car" ? (
          <Image
            source={instructionAssests}
            style={styles.imageDimension}
            resizeMode={"contain"}
            resizeMethod="scale"
          />
        ) : (
          <VideoPlayer
            ref={videoPlayerRef}
            video={instructionAssests}
            pauseOnPress={true}
            autoplay={false}
            disableSeek={true}
            loop={false}
            style={styles.iSVideo}
            onEnd={() => {
              playSound(getSoundName(index)); // the Audio instuctions will play now
            }}
          />
        )}
      </View>
      <View style={styles.instructViewRight}>
        <View style={{ flexDirection: "row" }}>
          {index !== 0 && (
            <TouchableOpacity
              hitSlop={{ top: 24, bottom: 24, right: 24, left: 24 }}
              style={styles.instructViewBackButton}
              onPress={onPrev}
            >
              <MIcon name="arrow-back" size={18} color={"#999999"} />
            </TouchableOpacity>
          )}
          <Text style={[styles.iSCurrentStep, style.muliRegLG]}>
            Steps {index + 1} /{" "}
            {totalSteps === 4 || totalSteps === 5 ? 3 : totalSteps}
          </Text>
        </View>
        <View style={{ flex: 0.9 }}>
          <Text style={[style.muliBoldDB, styles.iSTitle]}>
            {instructionTitle}
          </Text>
          {instructionData && (
            <BoldText
              style={[style.muliRegDB, styles.iSDetails]}
              text={instructionData}
              boldTextColor={Colors.darkBlack}
            />
          )}
          {instructionTitle === "Find your chassis number" && (
            <TouchableOpacity
              style={styles.instructViewEmbossedChassisButton}
              onPress={onNext}
            >
              <Text style={[style.muliBoldDB]}>
                What is embossed chassis no.?
              </Text>
              <View style={styles.instructViewEmbossedChassisView}>
                <Text style={[style.muliBoldDB, { color: Colors.borderBlack }]}>
                  i
                </Text>
              </View>
            </TouchableOpacity>
          )}
        </View>
        <PrimaryButton onPress={onProceed}>{okButtonText}</PrimaryButton>
      </View>
    </View>
  );
};

const InstructionsScreen = (props) => {
  const [stepCount, setStepCount] = useState(0);
  const [instructionArr, setInstructionArr] = useState(
    JSON.parse(props.instruction)
  );
  const [data, setData] = useState([]);
  const [stepsLength, setStepsLength] = useState(0);
  const [isLoading, setLoading] = useState(true);

  const flatListRef = React.useRef(null);
  const videoPlayerRef = React.useRef(null);

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

  useEffect(() => {
    const getVideoGuide = () => {
      // 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);
          console.log("sorttedinstruc", sortedInstructions);
          const genertedInstructions = generateInstructionData(
            sortedInstructions,
            isInternetReachable
          );
          console.log(
            "[InstructionScreen] . sortedInstruction generatedxs",
            JSON.stringify(genertedInstructions)
          );
          setData(genertedInstructions);
          setStepsLength(genertedInstructions?.length);
          setLoading(false);
        }
      }
    };
    getVideoGuide();
    playList = [];
    Orientation.lockToLandscape();
  }, []);

  useEffect(() => {
    flatListRef?.current?.scrollToIndex({
      animated: true,
      index: stepCount,
      viewOffset: 0,
      viewPosition: 0.5,
    });
  }, [stepCount]);

  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
      ) {
        videoPlayerRef.current.play();
        // 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
      ) {
        stopPreviousIfAny();
        const startCarPlayer = play(digitPreAudios["start_car"]);
        playList.push(startCarPlayer);
        // 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 = (instructionTitle) => {
    stopPreviousIfAny?.();

    if (instructionTitle === "Find your chassis number") {
      props.startRecording();
    }

    if (stepCount + 1 === stepsLength - 1) {
      props.startRecording();
    }
    /*
        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) {
      videoPlayerRef.current.stop();
      if (data[stepCount + 1]?.type === "video") {
        videoPlayerRef.current.play();
      }
      //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);
    } else {
      props.startRecording();
    }
  };

  const handleStepBack = () => {
    stopPreviousIfAny?.();
    if (stepCount > 0) {
      videoPlayerRef.current.stop();
      if (data[stepCount - 1]?.type === "video") {
        videoPlayerRef.current.play();
        // videoPlayerRef.current.resume();
      }
      //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 handleStepForward = () => {
    stopPreviousIfAny?.();
    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 getSoundName = (stepIndex) => {
    const soundString = data[stepIndex]?.okButtonText;
    console.log("($) getSoundName -> x", soundString);
    return soundString;
  };

  const onLayout = () => {
    flatListRef?.current?.scrollToIndex({
      animated: true,
      index: 0,
      viewPosition: 0.5,
    });
  };

  return (
    <Modal
      testID={"modal"}
      isVisible={true}
      style={{
        justifyContent: "flex-end",
        margin: 0,
      }}
      statusBarTranslucent
    >
      <View>
        {isLoading ? null : (
          <FlatList
            style={styles.flatListContainer}
            initialScrollIndex={0}
            onLayout={onLayout}
            data={data}
            keyExtractor={(item, index) => `${item?.title}_${index}`}
            renderItem={({ item, index }) => (
              <InstructView
                key={index}
                {...item}
                index={index}
                totalSteps={stepsLength}
                onNext={handleStepForward}
                onPrev={handleStepBack}
                onProceed={() => {
                  handleButtonPress(item.instructionTitle);
                }}
                playSound={playSound}
                getSoundName={getSoundName}
                videoPlayerRef={videoPlayerRef}
              />
            )}
            showsHorizontalScrollIndicator={false}
            horizontal
            pagingEnabled
            ref={flatListRef}
            scrollEnabled={false}
            contentContainerStyle={styles.flatListContentContainer}
            ListEmptyComponent={
              <View>
                <Text>Nothing to display</Text>
              </View>
            }
          />
        )}
      </View>
    </Modal>
  );
};
// iS = Instruction Screen
const styles = StyleSheet.create({
  iSContainer: {
    zIndex: zIndex_close_bonnet,
    width: "100%",
    justifyContent: "flex-end",
  },
  iSInstructionsContainer: {
    padding: 16,
    paddingTop: 8,
    height: SCREEN_WIDTH * 0.8,
  },
  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: 8,
  },
  iSDetailsView: {
    marginTop: 8,
    flex: 0.7,
    flexShrink: 1,
  },
  iSDetails: {
    fontSize: 14,
    flexShrink: 1,
    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,
  },
  chassisInstructViewParent: {
    flex: 1,
    width: SCREEN_WIDTH,
    padding: 32,
    justifyContent: "space-between",
  },
  chassisInstructViewHeader: { flex: 0.1, flexDirection: "row" },
  backButtonIcon: {
    backgroundColor: "#F5F5F5",
    borderRadius: 25,
    marginRight: 20,
    height: 24,
    width: 24,
    justifyContent: "center",
    alignItems: "center",
  },
  chassisInstructViewFooter: {
    flex: 0.8,
    flexDirection: "row",
    justifyContent: "space-between",
    padding: 8,
  },
  correctIconStyle: {
    backgroundColor: "#00AA55",
    position: "absolute",
    zIndex: 2,
    right: 5,
    margin: 10,
    top: 5,
  },
  incorrectIconStyle: {
    backgroundColor: "#EE0000",
    position: "absolute",
    zIndex: 2,
    right: 5,
    margin: 10,
    top: 5,
  },
  instructViewParent: {
    flex: 1,
    width: SCREEN_WIDTH * 0.98,
    padding: 32,
    flexDirection: "row",
    justifyContent: "space-between",
  },
  instructViewLeft: { flex: 0.45, borderRadius: 6 },
  instructViewRight: { flex: 0.5, justifyContent: "space-between" },
  instructViewBackButton: {
    backgroundColor: "#F5F5F5",
    borderRadius: 25,
    marginRight: 20,
  },
  instructViewEmbossedChassisButton: {
    backgroundColor: "#FFFAEB",
    padding: 8,
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "space-between",
    marginTop: 6,
  },
  instructViewEmbossedChassisView: {
    borderRadius: 25,
    borderWidth: 2,
    borderColor: Colors.digitYellow,
    height: 24,
    width: 24,
    alignItems: "center",
    justifyContent: "center",
  },
  flatListContentContainer: {
    marginTop: 60,
    backgroundColor: "white",
  },
  flatListContainer: {
    width: SCREEN_WIDTH,
  },
  imageDimension: { height: "100%", width: "100%" },
});

export default InstructionsScreen;
