import React, {
  forwardRef,
  useEffect,
  useMemo,
  useReducer,
  useState,
} from "react";
import {
  Animated,
  Easing,
  StyleSheet,
  View,
  Image,
  Dimensions,
  FlatList,
  Platform,
} from "react-native";
import Colors from "../common/Colors";
import {
  ANIM_DURATION,
  ANIMATION_TRACK,
  zIndex_moving_thumbnail,
  OBJ_WIDTH,
} from "./StencilAnimation";
// const pi_pose_strip = require("../../images/pi_pose_strip.png");
import {
  SCREEN_HEIGHT,
  SCREEN_WIDTH,
} from "react-native-digitcamera/src/common/Constants";
const pi_pose_strip = {
  uri: "https://d2h44aw7l5xdvz.cloudfront.net/CRM/PRM/car_angles-01.png",
};
const car_ech = require("../../src/common/Image/car_ech.png");
const car_chp = require("../../src/common/Image/car_chp.png");
const car_wnd = require("../../src/common/Image/car_wnd.png");
const car_fs = require("../../src/common/Image/car_fs.png");
const car_flc = require("../../src/common/Image/car_flc.png");
const car_ls = require("../../src/common/Image/car_ls.png");
const car_blc = require("../../src/common/Image/car_blc.png");
const car_bs = require("../../src/common/Image/car_bs.png");
const car_brc = require("../../src/common/Image/car_brc.png");
const car_rs = require("../../src/common/Image/car_rs.png");
const car_frc = require("../../src/common/Image/car_frc.png");
const car_dbd = require("../../src/common/Image/car_dbd.png");

var xData = [
  { source: car_ech, key: "1", focus: true },
  { source: car_chp, key: "2", focus: false },
  { source: car_fs, key: "3", focus: false },
  { source: car_flc, key: "4", focus: false },
  { source: car_ls, key: "5", focus: false },
  { source: car_blc, key: "6", focus: false },
  { source: car_bs, key: "7", focus: false },
  { source: car_brc, key: "8", focus: false },
  { source: car_rs, key: "9", focus: false },
  { source: car_frc, key: "10", focus: false },
  { source: car_fs, key: "11", focus: false },
  { source: car_wnd, key: "12", focus: false },
  { source: car_dbd, key: "13", focus: false },
];

const tickImg = require("../../src/common/Image/tick.png");

export const getStridesArr = (instruction) => {
  var strideArr = [];
  const instructionObj = JSON.parse(instruction);
  const videoObj = instructionObj.find((item) => item?.type == "video");
  if (videoObj) {
    const videoInstructionArr = videoObj?.TSurveyInstructions;
    if (videoInstructionArr) {
      const strideObjArr = videoInstructionArr?.filter(
        (item) => item?.type == "stride"
      );
      if (strideObjArr) {
        strideObjArr.map((item, index) => {
          strideArr.push({
            source: item?.instructionAssests,
            key: "" + index,
            focus: index == 0 ? true : false,
            isCaptured: false,
          });
        });
      }
    }
  }
  console.log("*** AnimationEaseLinear getStridesArr strideArr ", strideArr);
  if (strideArr && strideArr.length > 0) {
    return strideArr;
  } else {
    return xData;
  }
};

const AnimationEaseLinear = forwardRef((props, multiRef) => {
  const animFirst = new Animated.Value(0);
  const { mlCompleteRef, moveNextRef } = multiRef.current;
  const { instruction } = props;
  const [ref, setRef] = useState(null);
  const [data, setData] = useState(xData);
  const maxSize = Math.max(SCREEN_HEIGHT, SCREEN_WIDTH) / 2;

  const getStride = useMemo(() => {
    const strideArr = getStridesArr(instruction);
    setData(strideArr);
  }, [instruction]);

  const moveToCheckNextPose = (newPoseIndex) => {
    var focusIndex = newPoseIndex;
    console.log(
      "**** AnimationEaseLinear moveToCheckNextPose focusIndex : " + focusIndex
    );
    if (ref && data && data.length > 0) {
      if (focusIndex > data.length - 1) {
        focusIndex = 0;
        if (mlCompleteRef.current) {
          mlCompleteRef.current(false); // Calls stopScreenRecordingCallback from StencilAnimatin
        }
      }
      ref.scrollToIndex({
        animated: true,
        index: focusIndex,
        viewPosition: 0.2, // focused items projection view
      });
      const newData = data.map((item, index) => {
        const showTick = focusIndex > index ? true : false;
        if (focusIndex === index) {
          return { ...item, focus: true, isCaptured: showTick };
        } else {
          return { ...item, focus: false, isCaptured: showTick };
        }
      });
      setData(newData);
    }
  };

  useEffect(() => {
    moveNextRef.current = moveToCheckNextPose; // called from StencilAnimation -> posePeriodIntervalFun -> nextStencil
    // return ()=>{
    //   moveNextRef.current = undefined;
    // }
  }, [ref]);

  const renderItem = ({ item, index }) => {
    const img =
      item?.source &&
      typeof item?.source == "string" &&
      item?.source.includes("http")
        ? { uri: item?.source }
        : item?.source;

    return (
      <View style={{ width: OBJ_WIDTH }}>
        {item.focus && (
          <View
            style={{
              position: "absolute",
              backgroundColor: Colors.digitYellow,
              height: 5,
              width: "100%",
              borderBottomLeftRadius: 10,
              borderBottomRightRadius: 10,
            }}
          />
        )}
        <Image
          key={item?.key}
          style={[
            Platform.os == "ios" ? styles.stripImageIOS : styles.stripImageAND,
          ]}
          // style={{ width: OBJ_WIDTH, height: "100%", marginHorizontal: 2 }}
          source={img}
          onError={(error) =>
            console.log("*** AnimationEaseLinear img onError ", error)
          }
          resizeMode={Platform.os == "ios" ? "cover" : "center"}
        />
        {item.isCaptured && (
          <View style={styles.tick}>
            <Image
              key={item?.key}
              style={{ width: OBJ_WIDTH, height: "100%" }}
              source={tickImg}
              resizeMode="center"
            />
          </View>
        )}
      </View>
    );
  };

  return (
    <View style={[styles.mainView, { width: maxSize }]}>
      <FlatList
        style={{ width: maxSize }}
        contentContainerStyle={{ paddingRight: "90%" }}
        horizontal={true}
        data={data}
        ref={(ref) => {
          setRef(ref);
        }}
        renderItem={renderItem}
        // ItemSeparatorComponent={Divider}
        keyExtractor={(item) => item?.key}
      />
      {/* <Animated.View
        style={[styles.animView, { transform: [{ translateX: animFirst }] }]}
      /> */}
    </View>
  );
});

const styles = StyleSheet.create({
  mainView: {
    flex: 1,
    height: "15%",
    zIndex: 1000,
    marginTop: 0,
    width: "50%",
    position: "absolute",
    top: 0,
    left: "50%",
    justifyContent: "flex-end",
    backgroundColor: "black",
  },
  stripImageAND: {
    width: OBJ_WIDTH,
    height: "100%",
    marginHorizontal: 2,
  },
  stripImageIOS: {
    width: "70%",
    height: "90%",
    marginHorizontal: 2,
  },
  animView: {
    height: "100%",
    borderWidth: 2,
    borderColor: Colors.digitYellow,
    borderRadius: 5,
    width: "10%",
    backgroundColor: "transparent",
    position: "absolute",
  },
  stencilStyle: {
    width: "100%",
    height: "100%",
  },
  poseImage: {
    width: "100%",
    height: "100%",
    backgroundColor: "white",
  },
  tick: {
    position: "absolute",
    backgroundColor: "rgba(0,0,0,0.5)",
    width: "100%",
    height: "100%",
  },
});

export default AnimationEaseLinear;
