import { Alert } from "react-native";
import { is2Wflow } from "react-native-digitcamera/src/common/Constants";
import { getActivityid } from "react-native-digitcamera/src/common/Services/getActivityid";
import UploadFile from "react-native-digitcamera/src/Screens/UploadFile";
import { async } from "validate.js";
import Database from "../../../../../Components/common/DAsyncStorage";
import store from "react-native-digitcamera/src/redux/store";
import { NamedModal } from "react-native-digitcamera/src/common/GlobalModal";
import {
  callChassisPoseDetection,
  callPoseDetection,
  canCreateActivityId,
  canUpload,
  getCurrentActivity,
  getUserType,
  updateActivityId,
} from "react-native-digitcamera/src/Screens/OfflineFlow/CommonFunc";
import { startOfflineBackgroundUpload } from "react-native-digitcamera/src/Screens/SilentUpload/SilentUploadUtils";
import { initMediaFile } from "react-native-digitcamera/src/Screens/SilentUploadV2/DatabaseHelpers";
import { UELogEvent } from "react-native-digitcamera/src/common/libEventLog/UserExperior/LibUserExperior";
import {
  errorRecord,
  firebaseAttributes,
} from "react-native-digitcamera/src/common/libEventLog/libCrashlytics/libCrashlyticsEvent";
import { checkPoseDetection } from "react-native-digitcamera/src/common/poseDetection";
var sensorImageDetails = [];

export const CreateActivityId = async (
  activityDetails,
  updateReduxCallback,
  addSensorDataCallback
) => {
  try {
    console.log("Activity to be created : ", activityDetails);
    var vechicleData = await Database.get("PIVechicleData");
    const AppLoginStatus = await Database.get("AppLoginStatus");
    if (
      canCreateActivityId(activityDetails?.activityId) ||
      activityDetails?.activityId == undefined ||
      activityDetails?.activityId == null
    ) {
      console.log("**** CreateActivityId called");
      //API call
      console.log("In if     ", activityDetails?.activityId);
      const { getUserDetails } = require("../../common/Who");
      await getUserDetails();
      const {
        emailId,
        name,
        phoneNo,
        panHolderName,
        panNo,
        agentNumber,
      } = require("../../common/Who");
      const USERTYPE = AppLoginStatus?.userType;
      let body;
      var registrationNumber = activityDetails?.regNumber;
      var quoteNumber = activityDetails?.policyNumber;
      var activityTypeId = activityDetails?.activityTypeId;
      var toTutorial = vechicleData?.toTutorial;
      var toWithQuote = vechicleData?.toWithQuote;
      var regNumber;
      var userType = await getUserType();
      if (USERTYPE === "Customer") {
        body = {
          activityTypeId: activityTypeId,
          customerDetailData: {
            emailId: emailId,
            name: name,
            phoneNo: phoneNo,
          },
          licensePlateNumber: registrationNumber,
          previousPolicyExpired: true,
          quoteNumber: quoteNumber,
          requestedBy: userType,
          appName: "Quick Scan",
        };
      } else if (USERTYPE === "DealerOrAgent") {
        body = {
          activityTypeId: activityTypeId,
          customerDetailData: {
            emailId: emailId,
            name: name,
            phoneNo: phoneNo,
            panHolderName: panHolderName,
            panNo: panNo,
          },
          agentId: agentNumber,
          licensePlateNumber: registrationNumber,
          previousPolicyExpired: true,
          quoteNumber: quoteNumber,
          requestedBy: userType,
          appName: "Quick Scan",
        };
      }
      console.log("CreateActivity : body : ", body);
      console.log("CreateActivity : body : ", body.activityTypeId);
      var activityData = await getActivityid({ body });
      console.log(
        "activityData?.activityID : ",
        activityData?.activityID,
        activityData.activityTypeId
      );
      await updateActivityId(activityDetails, activityData?.activityID);

      var updatedRegistrationNumber =
        activityData?.additionalActivitiesList.filter((item) => {
          if (item.key == "Registration Number") {
            return item;
          }
        });
      let userNCB = activityData?.additionalActivitiesList.filter((item) => {
        if (item.key == "User NCB") {
          return item;
        }
      });
      if (updatedRegistrationNumber.length > 0) {
        console.log(
          "CreateActivityID.js : RegNumber Available : ",
          updatedRegistrationNumber
        );
        regNumber = updatedRegistrationNumber[0]?.value;
        console.log(
          "updatedRegistrationNumber >>> >> > :",
          updatedRegistrationNumber
        );

        await updateActivityKey(
          activityData.activityID,
          "regNumber",
          updatedRegistrationNumber[0]?.value
        );
      } else {
        console.log("CreateActivityID.js : RegNumber Available : ");
        regNumber = "";
      }
      /**
       * If getActivityId failed
       * then show failure modal
       */
      if (!activityData) {
        await updateActivityKey(
          activityData.activityID,
          "serviceFailure",
          true
        );
        await Database.set("PIReUploadFailed", "true");
        return;
      }

      if (activityData.flag === "Manual Inspection") {
        store.dispatch({
          type: "GLOBAL_MODAL_SHOW",
          payload: NamedModal.MANUAL_INSPECTION,
        });
        return;
      }

      console.log(
        "is2Wflow(activityData.activityTypeId",
        is2Wflow(activityData.activityTypeId),
        activityDetails,
        activityData?.activityID,
        activityData.activityTypeId
      );

      // only update current activity data in PIVechicleData
      if (is2Wflow(activityData.activityTypeId)) {
        try {
          console.log(
            "CreateActivityID.js : Update PIVechicleData started: ",
            regNumber
          );
          await Database.update("PIVechicleData", {
            activityId: activityData?.activityID,
            activityTypeId: activityData?.activityTypeId,
            licensePlateNumber: regNumber,
            toWithQuote: toWithQuote,
            toTutorial: toTutorial,
            quoteNumber: quoteNumber,
            ncb:
              userNCB === undefined || userNCB.length == 0
                ? 0
                : Number(userNCB[0].value),
            vechicleType: "",
          });
          console.log(
            "CreateActivityID.js : Update PIVechicleData End: ",
            regNumber
          );
          const PIVechicleData = await Database.get("PIVechicleData");
          console.log(
            "PIVechicleData : in CreateActivity.js : after creating new Activity ",
            PIVechicleData
          );
          await checkPoseDetection();
        } catch (error) {
          console.log(
            "Error: createActivityID  is2Wflow(activityData.activityTypeId) ",
            error
          );
        }
      }
      updateReduxCallback();
    }
  } catch (error) {
    console.log("Error in CreateActivityId.js ", error);
  }
};

// this function adds "value" agains a "key"  to a Activity in PIMediaStatus DB

// I'm using this to update if any of the service fails
//  /preinpsection & /instruction if failed
// then serviceFailure = true
const updateActivityKey = async (activityId, key, value) => {
  try {
    const pMediaStatus = await Database.get("PIMediaStatus");
    console.log(
      "updateActivityKey : activityId : key : value :",
      activityId,
      key,
      value
    );
    const nPIMediaStatus = pMediaStatus.map((item) => {
      if (item.activityId === activityId) {
        const newObj = item;
        newObj[key] = value;
        return newObj;
      } else {
        return item;
      }
    });
    Database.set("PIMediaStatus", nPIMediaStatus);
  } catch (error) {
    console.log("Error : CreateActivity : updateActivityKey :", error);
  }
};
