import { View, Text, StyleSheet } from "react-native";
import React, { useState } from "react";
import Header from "../common/Header";
import style from "../common/CommonStyle";

import {
  DIGIT_PAYMENT_CANCEL_URL,
  DIGIT_PAYMENT_SUCCESS_URL,
  UAT_DIGIT_FEED_BACK_PAGE_URL,
  PROD_DIGIT_FEED_BACK_PAGE_URL,
} from "../Api/ApiUrls";

import { async } from "validate.js";
import { generatePaymentLink } from "../common/Services/generatePaymentLink";
import { downloadPdf } from "../common/Services/downloadPdf";
import { downloadFileToDevice } from "../common/commonFunctions";

const ApprovedScreen = () => {
  useEffect(() => {
    callGetActivityForAutoPIDecision();
  }, []);

  const callGetActivityForAutoPIDecision = async () => {
    try {
      const data = await getActivityForAutoPIDecision({
        activityId: "91733011",
      });
      if (data != null || data.receivedActivities != null) {
        showTheScreensBasedOnAutoPIDecision(data);
      } else {
        Alert.alert("Something Went Wrong");
      }
    } catch (error) {
      console.log("Error in ", error);
    }
  };

  const showTheScreensBasedOnAutoPIDecision = (data) => {
    let isActivityApproved = data.receivedActivities.filter((item) => {
      if (item.key == "AutoPI-Decision") {
        return item;
      }
    });
    if (isActivityApproved[0]?.value == "Approved") {
      // if user PI is Approved
      //  handleVisibilityConditions("approve");
      showScreensBasedonConditions(data);
    } else {
      // if reinspection
    }
  };

  const showScreensBasedonConditions = (data) => {
    try {
      if (data.policyNumber != null || data.policyNumber != "") {
        let PIReason = data?.additionalActivitiesList?.filter((item) => {
          if (item.key == "PI Reason") {
            return item;
          }
        });

        let breakin = data?.additionalActivitiesList?.filter((item) => {
          if (item.key == "breakin") {
            return item;
          }
        });

        if (PIReason[0]?.key == "PI Reason") {
          if (PIReason[0]?.value == "breakin") {
            let policyNumber = data?.policyNumber;
            showDownloadPolicyPDFScreen(policyNumber);
          } else {
            if (PIReason[0]?.value == "Endorsement") {
              // open web view use this urls
              //   UAT_DIGIT_FEED_BACK_PAGE_URL,
              //  PROD_DIGIT_FEED_BACK_PAGE_URL,
            }
          }
        }
      }
    } catch (error) {
      console.log("Error in showScreensBasedonConditions()", error);
    }
  };

  const showDownloadPolicyPDFScreen = async (policyNumber) => {
    try {
      let body = {
        successReturnUrl: DIGIT_PAYMENT_SUCCESS_URL,
        applicationNumber: policyNumber,
        cancelReturnUrl: DIGIT_PAYMENT_CANCEL_URL,
      };
      const data = await generatePaymentLink({ body: body });
      let status = JSON.parse(data.message).responseBody.errorCode;
      console.log("Payment service Status code :", status);
      if (status == 200) {
        // generate payment link
        if (data != null) {
          try {
            var paymentLink = data;
            // navigate to web view
          } catch (error) {
            console.log("Error in genrate Payment link", error);
          }
        }
      } else {
        if (status == 400) {
          // genrate PDF
          showPDFScreen(policyNumber);
        }
      }
    } catch (error) {
      console.log("Error in showDownloadPolicyPDFScreen", error);
    }
  };

  const showPDFScreen = async (policyNumber) => {
    try {
      var body = {
        policyNumber: policyNumber,
      };
      const pdfData = await downloadPdf({ body: body });
      if (pdfData != null) {
        var pdfDownloadUrl = pdfData.quotePath;
        console.log("pdf url ", pdfDownloadUrl);
        let filename = `${policyNumber}.pdf`;
        console.log("^^^^^^^^", pdfDownloadUrl);
        downloadFileToDevice({ url: pdfDownloadUrl, filename });
      }
    } catch (error) {
      console.log("Error in showPDFScreen()", error);
    }
  };

  return (
    <View style={styles.ApprovedScreenContainer}>
      <Header hideArrowBackButton={true} shiftTitleToLeft={true} />
      <Text style={{ textAlign: "center" }}>Image</Text>
      <Text
        style={[
          style.muliExBoldDB,
          { fontSize: 20, textAlign: "center", marginTop: 20 },
        ]}
      >
        Yay! wasn't that quick?
      </Text>
      <Text
        style={[
          style.muliRegDB,
          { fontSize: 16, textAlign: "center", marginVertical: 8 },
        ]}
      >
        Your pre-inspection has been approved by Aria, out in-house bot.
      </Text>
    </View>
  );
};

export default ApprovedScreen;

const styles = StyleSheet.create({
  ApprovedScreenContainer: {
    flex: 1,
    backgroundColor: "white",
    justifyContent: "flex-start",
  },
});
