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 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.png",
    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_find.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;
};

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);

  useEffect(() => {
    // if (Orientation.getInitialOrientation() === "PORTRAIT") {
    //     Orientation.lockToLandscape()
    // }
    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"
        );
        const sortedInstructions = sortByDisplayOrder(imageTypeInstructions);
        console.log(
          "^^^^ Sorted Instructions data ^^^^^",
          JSON.stringify(sortedInstructions, null, "  ")
        );
        // setData(item?.TSurveyInstructions);
        setData(sortedInstructions);
      }
    }
  }, []);

  const handleButtonPress = () => {
    /*
        stepCount refers to the number of steps 
        intialized as 0 for to act as index for 
        intstructions array.
        */
    if (stepCount < 2) {
      /*
            Loads next instructions
            */
      setStepCount(stepCount + 1);
      setImageLoaded(false);
    } else {
      /*
            startRecording callback
            */
      props.startRecording();
    }
  };

  const handleStepBack = () => {
    if (stepCount > 0) {
      setStepCount(stepCount - 1);
    }
  };

  const handleStepForward = () => {
    if (stepCount < 2) {
      setStepCount(stepCount + 1);
    }
  };

  const handleOnInfoPress = () => {
    setStepCount(3);
    console.log(
      "($) InstructionsScreen, handleOnInfoPress, stepCount 3 data =>",
      data[stepCount]
    );
  };

  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={handleStepBack}
          >
            <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,
              }}
              // 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:
                  data !== undefined
                    ? data[stepCount + 1].instructionAssests
                    : DATA[stepCount + 1].instructionAssests,
              }}
              style={{ height: "100%", width: "100%" }}
            />
            <View style={styles.iSFetchingImageIndicator}>
              {/* <ImagePlaceholder /> */}
            </View>
          </View>
        </View>
      </View>
    );
  };

  return (
    <View style={styles.iSContainer}>
      {stepCount !== 3 && (
        <View style={styles.iSInstructionsContainer}>
          <View style={styles.iSImageContainer}>
            {/* Image Container */}
            <View style={styles.iSImageView}>
              <Image
                key={
                  data !== undefined
                    ? data[stepCount]?.surveyInstructionsId
                    : DATA[stepCount]?.surveyInstructionsId
                }
                source={{
                  uri:
                    data !== undefined
                      ? data[stepCount]?.instructionAssests
                      : DATA[stepCount]?.instructionAssests,
                }}
                // source={{ uri: props.instructionAssests === undefined ? data[stepCount].instructionAssests : props.instructionAssests }}
                style={styles.iSImage}
                onLoadEnd={() => setImageLoaded(true)}
                onLoadStart={() => setImageLoaded(false)}
              />

              {/* This indicator will show until image is fetched & displayed. */}
              {!imageLoaded && (
                <View style={styles.iSFetchingImageIndicator}>
                  <ImagePlaceholder />
                </View>
              )}
            </View>

            {/* Instructions Details & Action */}
            <View style={styles.iSInstructionsView}>
              {/* Instructions Steps,Title,Detailss */}
              <View style={styles.iSTitleDetailParent}>
                <View style={styles.iSStepTitle}>
                  <View style={styles.iSStepAction}>
                    <TouchableOpacity
                      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}/3</Text>
                    </Text>
                    <TouchableOpacity
                      style={{
                        backgroundColor:
                          stepCount === 2 ? "transparent" : "#F5F5F5",
                        borderRadius: 25,
                      }}
                      onPress={handleStepForward}
                    >
                      <MIcon
                        name="arrow-forward"
                        size={18}
                        color={stepCount === 2 ? "transparent" : "#999999"}
                      />
                    </TouchableOpacity>
                  </View>
                  <Text style={[style.muliBoldDB, styles.iSTitle]}>
                    {data !== undefined
                      ? data[stepCount]?.instructionTitle
                      : DATA[stepCount]?.instructionTitle}
                  </Text>
                </View>
                <View
                  style={[
                    styles.iSDetailsView,
                    {
                      flexDirection: "column",
                      justifyContent: "space-between",
                    },
                  ]}
                >
                  <BoldText
                    style={[style.muliRegDB, styles.iSDetails]}
                    text={
                      data !== undefined
                        ? data[stepCount]?.instructionData
                        : DATA[stepCount]?.instructionData
                    }
                    boldTextColor={Colors.darkBlack}
                  ></BoldText>

                  {/* <Text
                  style={[style.muliRegDB, styles.iSDetails]}
                  numberOfLines={6}
                > 
              </Text>*/}
                  <View>
                    {stepCount == 2 && (
                      <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}>
                <PrimaryButton onPress={handleButtonPress}>
                  {data !== undefined
                    ? data[stepCount]?.okButtonText
                    : DATA[stepCount]?.okButtonText}
                </PrimaryButton>
              </View>
            </View>
          </View>
        </View>
      )}
      {stepCount === 3 && embossedChassisInfoModal()}
    </View>
  );
};

// iS = Instruction Screen
const styles = StyleSheet.create({
  iSContainer: {
    // flex: 1,
    zIndex: 1000,
    width: "100%",
    justifyContent: "flex-end",
    backgroundColor: "transparent",
  },
  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",
  },
  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;
