import { View, Text, StyleSheet, Image } from "react-native";
import React, { useEffect, useState } from "react";
import Header from "./Header";
import style from "../common/CommonStyle";
import * as Progress from "react-native-progress";
const aria_image = require("../common/Image/aria_image.png");
import { getActivityForAutoPIDecision } from "../common/Services/getActivityForAutoPIDecision";
import { AutoPIProgress } from "../common/Services/autoPIProgress";

/*
Auto PI is true => 
1. true or false
2. call progress for 6 sec for 2 min
3. after getting value 12,call activity
4. activitiy=>auto pi approved or reject
5. after approved or reject show nps feedback rating
6. timeout when 2 min


*/

/*


[11:43 AM] Prakashagouda Patil

91733011 D056229051 WB58AS5491--
91481833 D055961017 GJ18BB1192
91752656 D056138835 RJ14LC2945
90186005 D053678981 KL08AT4050



[11:45 AM] Prakashagouda Patil

UP32LT5046

*/

const notes = [
  "Aria is our in-house Artificial Intelligence based \nsolution created to do more in less time. The name \nAria means ‘air’, just like air. it is an invisible support \nto our team.",
  "Our Service window is 9:00am to 7:00pm",
];

const eventTypes = [
  {
    eventType: "Approved",
    toScreen: "ApprovedScreen",
  },
  {
    eventType: "Reinspection",
    progress: 100,
    title: "An expert will be checking!",
    subTitleText:
      "Aria couldn't check some of the images you shared.No worries, we will send the images to our expert team, and they'll revert with a decision in 30 minutes!",
    bottomText: "You will receive an update via SMS and email shortly.",
  },
  {
    eventType: "Timeout",
    progress: 100,
    title: "An expert will be checking!",
    subTitleText:
      "Aria is taking longer than expected.No worries, we will send the images to our expert team, and they'll revert with a decision in 30 minutes!",
    bottomText: "You will receive an update via SMS and email shortly.",
  },
];

const NoteItem = (props) => {
  return (
    <View style={{ display: "flex", flexDirection: "row", margin: 4 }}>
      <Text style={{ marginRight: 10 }}>*</Text>
      <View>
        <Text style={[style.muliRegDB, { fontSize: 14, textAlign: "justify" }]}>
          {props.title}
        </Text>
      </View>
    </View>
  );
};

const AutoPIDecision = ({ navigation }) => {
  const [progress, setProgress] = useState(0);
  const [imagesProcessed, setImagesProcessed] = useState(0);
  const [currentEvent, setCurrentEvent] = useState(undefined);
  const [autoPIDecision, setAutoPIDecision] = useState();

  useEffect(() => {
    console.log("AutoPIDecision", autoPIDecision);
    if (autoPIDecision === "Approved" && imagesProcessed === 12) {
      // console.log("RUNNNINIGN")
      clearInterval(interval);
      navigation.navigate("ApprovedScreen", { interval: interval });
    }

    // Check if eligible for AutoPI
    if (imagesProcessed === 12) {
      /*
                QUERY activityId   
            */
      callAutoPIResult("91481833");
    }

    callAutoPIProgress();

    const interval = setInterval(() => {
      callAutoPIProgress();
    }, 6000);

    setTimeout(() => {
      setCurrentEvent(2); //Set Time Out event after 2 min //currently set to 30s
      clearInterval(interval);
    }, 30000);

    return () => {
      console.log(`clearing interval`);
      clearInterval(interval); //"97569282"
    };
  }, [progress, autoPIDecision]);

  //Get Progress Every 6 sec
  const callAutoPIProgress = async () => {
    try {
      /*
                @QUERY activityId
            */
      const data = await AutoPIProgress({ activityId: "91481833" });
      console.log(data.process_completed);
      setImagesProcessed(parseInt(data.process_completed));
      setProgress(convertToFloat(parseInt(data.process_completed), 16));
    } catch (error) {
      console.log("ERROR IN CALL AUTO PI PROGRESS", error);
      throw new Error(error.message);
    }
  };

  //Result of Auto PI
  const getResult = (activity) => {
    for (let idx in activity.receivedActivities) {
      if (activity.receivedActivities[idx].key === "AutoPI-Decision") {
        return activity.receivedActivities[idx].value;
      }
    }
    //
    return "Reinspection";
  };

  const callAutoPIResult = async (activityId) => {
    try {
      const activity = await getActivityForAutoPIDecision({ activityId });

      const result = await getResult(activity);

      if (result === "Approved") {
        setAutoPIDecision("Approved");
      } else if (result === "Reinspection") {
        setCurrentEvent(1);
      }
    } catch (error) {
      console.log("ERROR IN CALL AUTO PI RESULT", error);
      throw new Error(e);
    }
  };

  const convertToFloat = (value, imagesCount) => {
    return (parseInt(value) * 100) / imagesCount / 100;
  };

  return (
    <View style={styles.AutoPIDecisionContainer}>
      <Header />

      <View style={styles.AutoPIDecisionHeader}>
        <Text style={[style.muliRegDB, { fontSize: 18 }]}>
          {imagesProcessed}/16 Images
        </Text>

        <View style={styles.HeaderProgressView}>
          <Progress.Circle
            size={140}
            indeterminate={false}
            progress={currentEvent === undefined ? progress : 1}
            unfilledColor={"#DDDDDD"}
            thickness={10}
            color={currentEvent !== 2 ? "#FFBB00" : "#FA6400"}
            borderColor={"transparent"}
          />

          <Image
            style={{
              width: 50,
              height: 50,
              position: "absolute",
              left: 45,
              top: 40,
            }}
            source={
              currentEvent === undefined || currentEvent === 0
                ? aria_image
                : null
            }
          />
        </View>

        <Text style={[style.muliExBoldDB, { fontSize: 24, padding: 8 }]}>
          {currentEvent === undefined || currentEvent === 0
            ? "Hang in there"
            : eventTypes[currentEvent].title}
        </Text>

        {currentEvent === undefined || currentEvent === 0 ? (
          <Text
            style={[
              style.muliRegDB,
              {
                fontSize: 16,
                textAlign: "center",
                marginTop: 8,
                marginBottom: 30,
              },
            ]}
          >
            {" "}
            Our in-house bot <Text style={{ fontWeight: "bold" }}>Aria</Text> is
            checking the images you shared. Please give Aria a minute!{" "}
          </Text>
        ) : (
          <Text
            style={[
              style.muliRegDB,
              {
                fontSize: 16,
                textAlign: "center",
                marginTop: 8,
                marginBottom: 30,
              },
            ]}
          >
            {eventTypes[currentEvent].subTitleText}
          </Text>
        )}

        <Text style={[style.muliRegDB, { fontSize: 16, textAlign: "center" }]}>
          {currentEvent === undefined || currentEvent === 0
            ? "if she is unable to inspect any of the images, it will be referred to our expert who'll revert with a decision in 30 minutes"
            : eventTypes[currentEvent].bottomText}
        </Text>
      </View>

      <View style={styles.AutoPIDecisionFooter}>
        <View
          style={{
            borderWidth: 1,
            borderColor: "#DDDDDD",
            backgroundColor: "#F5F5F5",
            borderRadius: 8,
          }}
        >
          {notes.map((item) => {
            return <NoteItem title={item} />;
          })}
        </View>
      </View>
    </View>
  );
};

export default AutoPIDecision;

const styles = StyleSheet.create({
  AutoPIDecisionContainer: {
    flex: 1,
    backgroundColor: "white",
  },
  AutoPIDecisionHeader: {
    flex: 0.8,
    marginHorizontal: 16,
    paddingVertical: 10,
    justifyContent: "flex-start",
    alignItems: "center",
  },
  HeaderProgressView: {
    // height: 100
    marginTop: 10,
  },
  AutoPIDecisionFooter: {
    flex: 0.2,
    marginHorizontal: 16,
  },
});
