import React, {
  useEffect,
  useState,
  useRef,
  useReducer,
  forwardRef,
  startTransition,
} from "react";
import {
  StyleSheet,
  View,
  Text,
  FlexStyle,
  Animated,
  Easing,
} from "react-native";
import { zIndex_steps_instruction } from "./StencilAnimation";
import Orientation from "react-native-orientation";
import Colors from "react-native-digitcamera/src/common/Colors";
import { TouchableOpacity } from "react-native-gesture-handler";
import { SCREEN_HEIGHT } from "react-native-digitcamera/src/common/Constants";
import BoldText from "../common/BoldText";

const VDO = "VDO",
  nextInstruction = "nextInstruction",
  prevInstruction = "prevInstruction",
  reset = "reset";

const Steps = forwardRef((props, ref) => {
  const anim = new Animated.Value(0.01);
  const scaleAnimated = Animated.timing(anim, {
    toValue: 1,
    duration: 1300,
    easing: Easing.bounce,
    useNativeDriver: true,
  });

  const { instructionArr, nextStepCallback, prevStepCallback, resetCallback } =
    props;
  const originObj = instructionArr.filter((item) => item.imageName === VDO)[0];
  const stepInstructionObj = originObj?.TSurveyInstructions.filter(
    (item) => item.type === "instruction"
  );
  const stepsArr = stepInstructionObj.sort((obj1, obj2) => {
    let id1 = obj1.displayOrder;
    let id2 = obj2.displayOrder;
    return id1 - id2;
  });

  const originStep = stepsArr[0];
  const [stepsManager, moveToNextStep] = useReducer(stepsReducer, originStep);
  let showNormalText =
    stepsArr.findIndex(
      (obj) => obj.displayOrder === stepsManager.displayOrder
    ) == 0;

  function stepsReducer(state = originStep, action) {
    var newState = originStep;
    switch (action) {
      case nextInstruction:
        const oldIndex = stepsArr.findIndex(
          (obj) => obj.displayOrder === state.displayOrder
        );
        console.log("***** stepsReducer nextIndex " + oldIndex);
        var nextIndex = oldIndex + 1;
        if (nextIndex >= stepsArr.length) nextIndex = stepsArr.length - 1;
        console.log("***** stepsReducer nextIndex reset " + nextIndex);
        const newNextInstruction = stepsArr[nextIndex];
        newState = newNextInstruction;
        break;

      case prevInstruction:
        const prevOldIndex = stepsArr.findIndex(
          (obj) => obj.displayOrder === state.displayOrder
        );
        console.log("***** stepsReducer prevIndex " + prevOldIndex);
        var prevIndex = prevOldIndex - 1;
        if (prevIndex < 0) prevIndex = 0;
        console.log("***** stepsReducer prevIndex reset " + prevIndex);
        const newPrevInstruction = stepsArr[prevIndex];
        newState = newPrevInstruction;
        break;

      case reset:
        console.log("***** stepsReducer resetting ");
        newState = originStep;
        break;
    }
    console.log("***** stepsReducer showing:  " + newState.instructionData);
    return newState;
  }

  const moveToNextInstruction = () => {
    moveToNextStep(nextInstruction);
    return stepsManager;
  };

  const moveToPrevInstruction = () => {
    moveToNextStep(prevInstruction);
    return stepsManager;
  };

  const resetInstruction = () => {
    moveToNextStep(reset);
    return stepsManager;
  };

  useEffect(() => {
    scaleAnimated.start();
  }, [stepsManager.instructionData]);

  useEffect(() => {
    console.log("*** Steps: " + stepsArr.length);

    /*
     * Below landscapeToLeft() is being executed even after this component gets unmount
     * Such cases happend in OEM and Odometer component.
     * Odometer has lockToPortrait() so steps.js getting executed so does the landscapeToLeft()
     * so Odometer was rendering in landscape mode
     *
     * In OEM VehicleInspection.js also has portrait mode by default, but once the flow is done
     * We get to ThankYou.js on clicking on "Go To Homepage" button, we get back to VehicleInsepction.js
     * It also renders in Landscape mode, because steps still executes at back.
     *
     * So commenting below code, makes everthing fine & not rendering other components to landscape.
     * Also The StencilAnimation.js is in landscape by default so steps will render in landscape only.
     * Checked & Confirmed with unit testing.
     */

    // Orientation.lockToLandscapeLeft();

    if (nextStepCallback) {
      nextStepCallback.current = moveToNextInstruction;
    }
    if (prevStepCallback) {
      prevStepCallback.current = moveToPrevInstruction;
    }
    if (resetCallback) {
      resetCallback.current = resetInstruction;
    }
  });

  // const BoldText = (props) => {
  //   var arr = props.text.split(" ");
  //   const reducer = (acc, cur, index) => {
  //     let prevVal = acc[acc.length - 1];
  //     if (prevVal && prevVal.startsWith("<b>") && !prevVal.endsWith("</b>")) {
  //       acc[acc.length - 1] = prevVal + " " + cur;
  //     } else {
  //       acc.push(cur);
  //     }
  //     return acc;
  //   };
  //   var text = arr.reduce(reducer, []);
  //   return (
  //     <Text style={[styles.instructionText, props.style]}>
  //       {text.map((text) => {
  //         if (text.startsWith("<b>")) {
  //           return (
  //             <Text
  //               style={[styles.instructionText, { fontFamily: "Muli-Black" }]}
  //             >
  //               {text.replace("<b>", "").replace("</b>", "")}{" "}
  //             </Text>
  //           );
  //         }
  //         return `${text} `;
  //       })}
  //     </Text>
  //   );
  // };

  return (
    <View style={styles.mainView}>
      {showNormalText ? (
        <View style={styles.instructionView}>
          <BoldText
            text={stepsManager.instructionData}
            boldTextColor={Colors.white}
          ></BoldText>
        </View>
      ) : (
        <Animated.View
          style={[styles.instructionView, { transform: [{ scale: anim }] }]}
        >
          {/* <View style={styles.instructionView}> */}
          <BoldText
            key={stepsManager.displayOrder}
            text={stepsManager.instructionData}
            boldTextColor={Colors.white}
          ></BoldText>
          {/* </View> */}
        </Animated.View>
      )}
    </View>
  );
});

const styles = StyleSheet.create({
  mainView: {
    position: "absolute",
    zIndex: zIndex_steps_instruction,
    width: "100%",
    height: "100%",
    backgroundColor: "transparent",
    justifyContent: "flex-end",
  },
  instructionView: {
    alignSelf: "center",
    height: "10%",
    marginBottom: 0,
    marginHorizontal: 10,
    width: "70%",
    borderRadius: 300,
    justifyContent: "center",
    alignSelf: "baseline",
    backgroundColor: "rgba(0,0,0,0.5)",
  },
  instructionText: {
    marginHorizontal: 10,
    color: Colors.white,
    fontFamily: "Muli-Regular",
    fontSize: 13,
  },
});
export default Steps;
