/*
RCBPreview.
Flow => 

Navigate to this screen from tutorial
1.capture one photo redirect back to rcb
    -> capture->stencilanimation->proceed->check for rcb1 ->  dispatch uri ->back to rcbpreview
2.capture second photo redirect back to rcb
    -> capture->stencilanimation->proceed->check for rcb2 -> dispatch uri ->back to rcbpreview
3.capture n photo redirect back to rcb
    -> capture->stencilanimation->proceed->check for rcbN -> dispatch uri ->back to rcbpreview
4. only clicking on proceed, run next stencil.

changes in PreviewMedia,StencilAnimation,RCBPreview.
*/

import React, { useEffect, useState } from "react";
import {
  Text,
  View,
  SafeAreaView,
  Platform,
  StyleSheet,
  Image,
  Dimensions,
  ScrollView,
  StatusBar,
  FlatList,
} from "react-native";
import Orientation from "react-native-orientation";
import Carousel from "react-native-snap-carousel";
import {
  PrimaryButton,
  DashedButton,
} from "react-native-digitcamera/src/common/ThemedComponents";
import Header from "./Header";
import Database from "../../../../Components/common/DAsyncStorage";
import style from "../../../../Components/common/CommonStyle";
import { useSelector, useDispatch } from "react-redux";
const camera = require("react-native-digitcamera/src/common/Image/camera.png");
const deleteIcon = require("react-native-digitcamera/src/common/Image/deleteIcon.png");
import IIcon from "react-native-vector-icons/Ionicons";
import {
  UELogEvent,
  UELogMessage,
} from "../common/libEventLog/UserExperior/LibUserExperior";

const iOS = Platform.OS === "ios";

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

/* Local Image or Remote */
let IS_LOCAL = false;

const rcBookData = [
  {
    name: "RCB1",
    image: "https://cdn.godigit.com/digitEdgeAssets/Motor/4W_PI_RCB1_V2.jpg",
    info: "RC FRONT SAMPLE",
  },
  {
    name: "RCB2",
    image: "https://cdn.godigit.com/digitEdgeAssets/Motor/4W_PI_RCB2_V2.jpg",
    info: "RC BACK SAMPLE",
  },
];

let ACTIVITY_ID;
var ProceedCallback_Global; // temp solution
const RCBPreviewScreen = ({ navigation, route }) => {
  const { ProceedCallback } = route.params;
  if (ProceedCallback) {
    ProceedCallback_Global = ProceedCallback;
  }
  const [isAddMoreEnable, setIsAddMoreEnable] = useState(true);
  const [isProceedEnable, setIsProceedEnable] = useState(false);
  const [RCBData, setRCBData] = useState();

  const dispatch = useDispatch();

  /* Fetch captured RCB images from Redux */
  const RCBUris = useSelector((state) => state.rcbPreviewData.rcbPreviewData);
  console.log("***RCBPreviewScreen *RCBUris", RCBUris);

  /* RCB1 */
  const RCB1Image = RCBUris.find((item) => item.name === "RCB1");
  console.log("***RCBPreviewScreen, RCB1Image", RCB1Image);
  /* RCB2 */
  const RCB2Image = RCBUris.find((item) => item.name === "RCB2");
  console.log("***RCBPreviewScreen, RCB2Image", RCB2Image);
  /* Other RC Images*/
  const MoreRCBImages = RCBUris.filter((item) => item.info === "RC More Pages");
  console.log("***RCBPreviewScreen, More RC Images", MoreRCBImages);

  if (RCBUris.length !== 0) {
    IS_LOCAL = true;
  }
  StatusBar.setBackgroundColor("white");
  StatusBar.setBarStyle("dark-content");

  useEffect(() => {
    /* enable add more photos button once both rcb1 & rcb2 images are available */
    /* also enable proceed button */
    if (RCB1Image === undefined || RCB2Image === undefined) {
      setIsAddMoreEnable(true);
      setIsProceedEnable(false);
    } else {
      setIsAddMoreEnable(false);
      setIsProceedEnable(true);
    }
  }, [RCB1Image, RCB2Image]);

  useEffect(() => {
    /* Imported Component Static Methods */
    Orientation.lockToLandscapeLeft();

    /* Component Methods */
    SCREEN_WIDTH = getMinWidth();
    getActivityId();
    getRCBInstructions();

    /* listeners */
    if (!iOS) {
      const Immersive = require("react-native-immersive").Immersive;
      Immersive.setImmersive(true);
    }

    /* unsubscribing listeners */
    // for re-render immersive
    let unsubscribe = navigation.addListener("focus", () => {
      if (!iOS) {
        const Immersive = require("react-native-immersive").Immersive;
        Immersive.setImmersive(true);
      }
    });

    return () => {
      unsubscribe();
    };
  }, []);

  /* Component Methods */

  /* Fetching Activity Id */
  const getActivityId = async () => {
    const VehicleData = await Database.get("PIVechicleData");
    ACTIVITY_ID = VehicleData?.activityId;
    console.log("^^^RCBPreviewScreen. getActivityId ", ACTIVITY_ID);
  };
  /* Fetching RCB Instruction */
  const getRCBInstructions = async () => {
    UELogEvent("RCBPreviewScreen.js getRCBInstructions. ", {
      data: "Dataa",
    });
    var instructionInDb = await Database.get("PIVechicleInstruction");
    const instructionArr = JSON.parse(instructionInDb?.instuction);

    let item = instructionArr.filter((item) => item.imageName.includes("RCB"));
    let newRCBData = [];
    if (item !== undefined && item.length !== 0) {
      /* once received remote assets we set IS_LOCAL to false*/
      IS_LOCAL = false;
      item.forEach((item) => {
        let RCBItem = {
          name: item.imageName,
          image: item.stepAssests,
          info: `RC ${item.imageName === "RCB1" ? "FRONT" : "BACK"} SAMPLE`,
        };
        newRCBData.push(RCBItem);
      });
    }
    setRCBData([...newRCBData]);
  };

  const handleRCBFrontPage = () => {
    dispatch({
      type: "SET_CURRENT_IMAGE",
      payload: "RCB1",
    });
    console.log("*** RCBPreviewScreen handleRCBFrontPage before call ");
    if (ProceedCallback_Global) {
      ProceedCallback_Global();
    }
  };

  const handleRCBBackPage = () => {
    dispatch({
      type: "SET_CURRENT_IMAGE",
      payload: "RCB2",
    });
    console.log("*** RCBPreviewScreen handleRCBBackPage before call ");
    if (ProceedCallback_Global) {
      ProceedCallback_Global();
    }
  };

  const handleRCBMorePage = () => {
    dispatch({
      type: "SET_CURRENT_IMAGE",
      payload: "MORE",
    });
    console.log("*** RCBPreviewScreen handleRCBMorePage before call ");
    if (ProceedCallback_Global) {
      ProceedCallback_Global();
    }
  };

  const handleDeleteImage = (name) => {
    // run dispatch to delete images from redux
    dispatch({
      type: "DELETE_RCB_IMAGE_BY_TITLE",
      payload: name,
    });
  };

  const handleProceed = () => {
    // Go back to toturial
    navigation.navigate("Toturial", { fromRCB: true });
  };

  /* Sub Components */
  const DashedButtonsItem = ({ item }) => {
    return (
      <DashedButton
        key={"" + item?.name}
        Title={`${ACTIVITY_ID}_${item.name}`}
        RightImage={deleteIcon}
        leftIcon={<IIcon name="checkmark" color={"green"} size={24} />}
        onDeletePress={() => {
          handleDeleteImage(item.name);
        }}
        buttonTextStyle={{ alignItems: "flex-start" }}
        buttonLayoutStyle={{ marginLeft: 0, marginRight: 0 }}
      />
    );
  };
  const _renderRcBookData = ({ item, index }) => {
    return (
      // Image View
      <View style={{ flex: 1, marginRight: 12 }}>
        {item.image == undefined ? null : (
          <View style={styles._renderBookItemImageView}>
            {item.image && (
              <Image
                source={{ uri: item.image }}
                resizeMethod={"scale"}
                resizeMode="cover"
                style={styles._renderBookItemImage}
              />
            )}
          </View>
        )}
        <Text style={[style.muliRegLG, styles._renderBookItemText]}>
          {item.info}
        </Text>
      </View>
    );
  };
  var myData = RCBUris.length === 0 ? RCBData : RCBUris;
  if (myData == undefined || myData == null) {
    myData = [];
  }
  return (
    <SafeAreaView
      edges={iOS ? ["top", "bottom", "right"] : []}
      style={styles.safeArea}
    >
      <View style={{ flex: 1, justifyContent: "space-between" }}>
        {/* Header */}
        <View style={{ flex: 0.1 }}>
          <Header
            showTitle={"RC Book/Card"}
            hideArrowBackButton={false}
            onbackPress={() => {
              navigation.goBack();
            }}
            onlanguagechange={() => {
              forceUpdate();
            }}
            titleStyle={{ fontSize: 20 }}
          />
        </View>
        {/* Body */}
        <View style={styles.bodyView}>
          {/* Image Preview */}
          <View style={styles.imagePreviewView}>
            <Carousel
              layout="default"
              data={myData}
              renderItem={_renderRcBookData}
              sliderWidth={SCREEN_WIDTH}
              itemWidth={SCREEN_WIDTH * 0.9}
              // layoutCardOffset={`12`}
              activeSlideAlignment={"start"}
              inactiveSlideScale={0}
              autoplay={true}
              loop={true}
            />
          </View>

          {/* Actions */}
          <View style={styles.actionView}>
            {/* Title */}
            <View style={styles.titleView}>
              <Text style={[style.muliBoldDB, styles.title]}>
                Please upload RC Book images
              </Text>
            </View>
            <ScrollView style={styles.buttonsView}>
              {/* RC Front Page */}
              <View style={styles.scrollViewActionItem}>
                <Text style={[style.muliBoldDB, styles.buttonTitle]}>
                  RC Front Page
                </Text>

                {/* Once received captured image show dashed button with checkmark, otherwise primary button */}

                {RCB1Image !== undefined ? (
                  <DashedButton
                    Title={`${ACTIVITY_ID}_${RCB1Image.name}`}
                    RightImage={deleteIcon}
                    leftIcon={
                      <IIcon name="checkmark" color={"green"} size={24} />
                    }
                    onDeletePress={() => {
                      handleDeleteImage("RCB1");
                    }}
                    buttonTextStyle={{ alignItems: "flex-start" }}
                    buttonLayoutStyle={{ marginLeft: 0, marginRight: 0 }}
                  />
                ) : (
                  <PrimaryButton
                    style={styles.primaryButton}
                    onPress={handleRCBFrontPage}
                    icon={({ color, size }) => {
                      return (
                        <Image
                          source={camera}
                          style={{ width: 30, height: 30 }}
                        />
                      );
                    }}
                  >
                    {"Capture Image"}
                  </PrimaryButton>
                )}
              </View>

              {/* RC Back Page */}
              <View style={styles.scrollViewActionItem}>
                <Text style={[style.muliBoldDB, styles.buttonTitle]}>
                  RC Back Page
                </Text>
                {RCB2Image ? (
                  <DashedButton
                    Title={`${ACTIVITY_ID}_${RCB2Image.name}`}
                    RightImage={deleteIcon}
                    leftIcon={
                      <IIcon name="checkmark" color={"green"} size={24} />
                    }
                    onDeletePress={() => {
                      handleDeleteImage("RCB2");
                    }}
                    buttonTextStyle={{ alignItems: "flex-start" }}
                    buttonLayoutStyle={{ marginLeft: 0, marginRight: 0 }}
                  />
                ) : (
                  <PrimaryButton
                    style={styles.primaryButton}
                    onPress={handleRCBBackPage}
                    icon={({ color, size }) => {
                      return (
                        <Image
                          source={camera}
                          style={{ width: 30, height: 30 }}
                        />
                      );
                    }}
                  >
                    {"Capture Image"}
                  </PrimaryButton>
                )}
              </View>

              <View style={styles.scrollViewActionItem}>
                <Text style={[style.muliBoldDB, styles.buttonTitle]}>
                  Other RC Pages{" "}
                  <Text style={[style.muliRegLG, { fontSize: 10 }]}>
                    (if any)
                  </Text>
                </Text>
                {MoreRCBImages.length !== 0 &&
                  MoreRCBImages?.map((item) => {
                    return DashedButtonsItem({ item });
                  })}
                <PrimaryButton
                  style={[
                    styles.primaryButton,
                    isAddMoreEnable ? styles.primaryButtonDisabled : {},
                  ]}
                  onPress={handleRCBMorePage}
                  disabled={isAddMoreEnable} /* @Change */
                >
                  {"+   Add Photos"}
                </PrimaryButton>
              </View>
            </ScrollView>
            <View style={styles.proceedButton}>
              <PrimaryButton
                onPress={handleProceed}
                disabled={!isProceedEnable} /* @Change */
                style={[
                  !isProceedEnable ? { backgroundColor: "#DDDDDD" } : {},
                ]} /* @Change */
              >
                {"Proceed"}
              </PrimaryButton>
            </View>
          </View>
        </View>
      </View>
    </SafeAreaView>
  );
};

export default RCBPreviewScreen;

const styles = StyleSheet.create({
  safeArea: {
    flex: 1,
    backgroundColor: "white",
  },
  scrollViewActionItem: {
    marginBottom: 8,
  },
  _renderBookItemImageView: {
    flex: 1,
    borderWidth: 2,
    borderColor: "#DDDDDD",
    borderRadius: 8,
    height: SCREEN_WIDTH / 2,
  },
  _renderBookItemImage: {
    width: "100%",
    height: "100%",
    resizeMode: "stretch",
    borderRadius: 8,
  },
  _renderBookItemText: {
    marginTop: 4,
    fontSize: 12,
  },
  bodyView: {
    flex: 0.9,
    flexDirection: "row",
    justifyContent: "space-between",
    marginHorizontal: 16,
    paddingVertical: 8,
  },
  imagePreviewView: {
    flex: 0.45,
    paddingVertical: 8,
  },
  actionView: {
    flex: 0.45,
  },
  titleView: {
    paddingHorizontal: 16,
  },
  buttonsView: {
    paddingVertical: 8,
    paddingHorizontal: 16,
  },
  title: {
    fontSize: 20,
  },
  buttonTitle: {
    fontSize: 14,
    fontWeight: "700",
  },
  primaryButton: {
    marginTop: 5,
    backgroundColor: "white",
    borderColor: "#000000",
    borderWidth: 1,
    borderRadius: 4,
  },
  primaryButtonDisabled: {
    /* @Change */ backgroundColor: "#FAFAFA",
    borderWidth: 1,
    borderColor: "#DDDDDD",
    color: "#444444",
  },
  proceedButton: {
    paddingVertical: 8,
    paddingHorizontal: 16,
  },
});
