import React, { Component, useEffect, useState } from "react";
import {
  StyleSheet,
  View,
  Text,
  TouchableOpacity,
  Image,
  Button,
  LogBox,
  StatusBar,
  Linking,
  BackHandler,
} from "react-native";
import { TextInput, HelperText } from "react-native-paper";
import Colors from "../common/Colors";
import { getDocumentLast } from "../common/Services/DocumentLast";
import {
  thank_you,
  your_preins_apprvd,
  preinsp_com_will_update,
  DIRECT_PORTAL_AGENTCODE,
  super_thank_you,
  SCREEN_WIDTH,
  SCREEN_HEIGHT,
  is2Wflow,
  isCVFlow,
} from "../common/Constants";
import { translate } from "react-native-digitcamera/src/common/localize/i18n";
import { PrimaryButton, Spinner } from "../common/ThemedComponents";
import Orientation from "../../../react-native-orientation";
import { useDispatch, useSelector } from "react-redux";
import { genrateSensorFile } from "react-native-digitcamera/src/common/SensorData";
import { dispatch } from "react-native-digitcamera/src/common/RootNavigation";
import { ScrollView } from "react-native-gesture-handler";
import Database from "../../../../Components/common/DAsyncStorage";

import {
  errorRecord,
  firebaseAttributes,
} from "react-native-digitcamera/src/common/libEventLog/libCrashlytics/libCrashlyticsEvent";
import {
  UELogEvent,
  UELogMessage,
} from "../common/libEventLog/UserExperior/LibUserExperior";
import { submitPI } from "react-native-digitcamera/src/common/Services/submitPI";

const cross = require("../common/Image/cross.png");
const thankyou_done = require("../common/Image/thankyou_done.png");
const call = require("../common/Image/call.png");
const mail = require("../common/Image/mail.png");
var toWithQuote;
var toTutorial;
var activityID, activityTypeId, licensePlateNumber, quoteNumber;

const ThankYou = ({ navigation, route }) => {
  const [thankYou, SetThankYou] = useState("All Done!");
  const [isLoading, SetIsLoading] = useState(true);
  const [message, SetMessage] = useState(
    "You have successfully completed the pre-inspection process. Once we have ensured everything is all right, we’ll get back to you."
  );

  const { sensorDataInfo } = useSelector((state) => state.sensorImageData);
  const dispatch = useDispatch();
  useEffect(() => {
    Orientation.lockToPortrait();
    // API call
    documentLast();
    // disabled back handler
    const backHandler = BackHandler.addEventListener(
      "hardwareBackPress",
      () => {
        return true;
      }
    );

    return () => {
      backHandler.remove();
    };
  }, []);

  // document last API call
  const documentLast = async () => {
    try {
      var vechicleData = await Database.get("PIVechicleData");
      toWithQuote = vechicleData?.toWithQuote;
      toTutorial = vechicleData?.toTutorial;
      console.log("route.params.props.navigation", toWithQuote, toTutorial);

      activityID = vechicleData?.activityId;
      activityTypeId = vechicleData?.activityTypeId;
      licensePlateNumber = vechicleData?.licensePlateNumber;
      quoteNumber = vechicleData?.quoteNumber;
      console.log(
        "*** ThankYou documentLast: activityID: " +
          activityID +
          " activityTypeId: " +
          activityTypeId +
          " licensePlateNumber: " +
          licensePlateNumber +
          " quoteNumber: " +
          quoteNumber
      );

      UELogEvent("documentLast call started..", {
        "Activity Id": JSON.stringify(activityID),
        "Activity Type Id": JSON.stringify(activityTypeId),
        "License Plate Number": JSON.stringify(licensePlateNumber),
        "Quote Number": JSON.stringify(quoteNumber),
        "Sensor Data Info": JSON.stringify(sensorDataInfo),
        isLast: "true",
        source: "DIGITEDGE",
      });
      SetIsLoading(true);
      await genrateSensorFile(
        activityID,
        activityTypeId,
        licensePlateNumber,
        quoteNumber,
        sensorDataInfo,
        async () => {
          if (canGoVideoPi(activityTypeId)) {
            try {
              var submitPIResp = await submitPI({
                body: {
                  activityId: activityID,
                },
              });
              console.log(
                "submitPIResp",
                JSON.stringify(submitPIResp, null, "  ")
              );
            } catch (error) {
              console.log("Error in SubmitPI Api ", error);
            }

            // As per new logic not required to call the /last service

            // const DocumentLastData = await getDocumentLast({
            //   body: {
            //     activityId: activityID,
            //     isLast: true,
            //     source: "DIGITEDGE",
            //   },
            // });
            // UELogEvent("documentLast Call ended in try", {
            //   "Document Last Response": JSON.stringify(
            //     DocumentLastData,
            //     null,
            //     "  "
            //   ),
            // });
            // console.log(
            //   "Document last Responce",
            //   JSON.stringify(DocumentLastData, null, "  ")
            // );
            // renderMsgToScreen(DocumentLastData);
          }
          // for 2W and CV
          if (is2Wflow(activityTypeId) || isCVFlow(activityTypeId)) {
            const DocumentLastData = await getDocumentLast({
              body: {
                activityId: activityID,
                isLast: true,
                source: "DIGITEDGE",
              },
            });
            UELogEvent("documentLast Call ended in try", {
              "Document Last Response": JSON.stringify(
                DocumentLastData,
                null,
                "  "
              ),
            });
            console.log(
              "Document last Responce",
              JSON.stringify(DocumentLastData, null, "  ")
            );
            renderMsgToScreen(DocumentLastData);
          }
        }
      );
      SetIsLoading(false);
    } catch (error) {
      UELogEvent("documentLast Call ended in catch", {
        error: JSON.stringify(error),
      });
      firebaseAttributes(error);
      errorRecord(error);
    }
  };

  // thankyou msg
  const renderMsgToScreen = (DocumentLastData) => {
    const { approved, agentCode } = DocumentLastData;
    if (approved != null) {
      if (approved.toUpperCase() == "true") {
        if (agentCode == DIRECT_PORTAL_AGENTCODE) {
          SetThankYou(super_thank_you);
          SetMessage(your_preins_apprvd);
        } else {
          SetThankYou(super_thank_you);
          SetMessage(your_preins_apprvd);
        }
      } else {
        SetThankYou(thank_you);
        SetMessage(preinsp_com_will_update);
      }
    } else {
      SetThankYou(thank_you);
      SetMessage(preinsp_com_will_update);
    }
  };

  const clearRedux = () => {
    try {
      dispatch({
        type: "CLEAR_ACTIVITY_DATA",
      });
      dispatch({
        type: "CLEAR_IMAGE_CLICKED_COUNT_REDUX",
      });
      dispatch({
        type: "CLEAR_LAST_DATA_REDUX",
      });
      dispatch({
        type: "CLEAR_SENSOR_DETAILS_REDUX",
      });
      dispatch({
        type: "CLEAR_UPLOAD_IMAGE_REDUX",
      });
      dispatch({
        type: "CLEAR_UPLOAD_IMAGE_DATA_REDUX",
      });
      dispatch({
        type: "CLEAR_VEHICLE_DETAILS_REDUX",
      });
      dispatch({
        type: "CLEAR_RETRY_COUNT_REDUX",
      });
      dispatch({
        type: "CLEAR_RETRY_IMAGE_STATE",
      });
      dispatch({
        type: "CLEAR_RCB_DATA",
      });
    } catch (error) {
      firebaseAttributes(error);
      errorRecord(error);
    }
  };

  const clearAllRealmData = async () => {
    try {
      await Database.remove("PIOfflineData");
      await Database.remove("PIVechicleInstruction");
      await Database.update("PIRetryCount", {
        retryCount: 0,
        index: 0,
        isAddNewImageData: false,
      });
      await Database.remove("PILocation");
      await Database.update("PIStartOver", {
        isStartOver: true,
      });
      await Database.update("PIINDEX", {
        lastIndex: 0,
      });
      await Database.update("PIclickedCount", {
        clickedCount: 0,
      });
      await Database.update("PIUploadedCount", {
        uploadedCount: 0,
      });
      await Database.remove("PIVideoCompleteStatus");
    } catch (error) {
      errorRecord(error);
      firebaseAttributes(error);
    }
  };

  const addRealmVechicleData = async () => {
    await Database.update("PICompleteStatus", {
      piStatus: true,
    });
  };

  return (
    <View style={styles.main}>
      <Spinner loading={isLoading} />
      <ScrollView>
        <View style={styles.subView}>
          {/* thank you msg */}
          <View style={styles.ThankYoumsgView}>
            {/* close image */}
            <TouchableOpacity
              onPress={async () => {
                try {
                  if (toWithQuote) {
                    if (toTutorial) {
                      route.params.props.navigation.navigate(
                        route?.params?.navigateBackToManualPI
                      );
                    } else {
                      navigation.navigate(route?.params?.navigateBackTo);
                    }
                  } else {
                    route.params.props.navigation.navigate(
                      route.params.navigateBackToPostplanPreviousPolicy
                    );
                  }
                  await clearRedux();
                  await clearAllRealmData();
                  addRealmVechicleData();
                } catch (error) {
                  console.log("Error in cross icon ", error);
                }
              }}
            >
              <Image source={cross} style={{ height: 16, width: 16 }} />
            </TouchableOpacity>
            {/* thank you msg */}
            <View style={styles.thankyoumsg}>
              <Image
                source={thankyou_done}
                style={{
                  height: 52,
                  width: 60,
                  marginLeft: 4,
                  resizeMode: "contain",
                  marginBottom: 24,
                }}
              />
              <Text style={styles.allDoneText}>{translate("All Done!")}</Text>
              <Text style={styles.PImsg}>{message}</Text>
              <PrimaryButton
                style={{ marginTop: SCREEN_HEIGHT / 3 }}
                onPress={async () => {
                  console.log("toWithQuote", toWithQuote, toTutorial);
                  if (toWithQuote) {
                    if (toTutorial) {
                      route.params.props.navigation.navigate(
                        route.params.navigateBackToManualPI
                      );
                    } else {
                      navigation.navigate(route?.params?.navigateBackTo);
                    }
                  } else {
                    route.params.props.navigation.navigate(
                      route.params.navigateBackToPostplanPreviousPolicy
                    );
                  }
                  clearRedux();
                  await clearAllRealmData();
                  addRealmVechicleData();
                }}
              >
                {translate("Go to Homepage")}
              </PrimaryButton>
            </View>
          </View>
          {/* need help view */}
          <View style={styles.needHelpView}>
            <Text style={styles.needHelpText}>{translate("NEED HELP?")}</Text>
            {/* mail button */}
            <TouchableOpacity
              onPress={() => {
                Linking.openURL(`mailto:${"hello@godigit.com"}`);
              }}
            >
              <View style={styles.buttonStyle}>
                <Image
                  source={mail}
                  style={{ width: 24, height: 24, marginLeft: 12 }}
                />
                <Text style={styles.buttonText}>{"hello@godigit.com"}</Text>
              </View>
            </TouchableOpacity>
            {/* call button */}
            <TouchableOpacity
              onPress={() => {
                Linking.openURL(`tel:${"1800 103 4448"}`);
              }}
            >
              <View style={styles.buttonStyle}>
                <Image
                  source={call}
                  style={{ width: 24, height: 24, marginLeft: 12 }}
                />
                <Text style={styles.buttonText}>{"1800 103 4448"}</Text>
              </View>
            </TouchableOpacity>
          </View>
        </View>
      </ScrollView>
    </View>
  );
};
export default ThankYou;

const styles = StyleSheet.create({
  main: {
    flex: 1,
    backgroundColor: "#FFFFFF",
  },
  subView: {
    margin: 18,
    flex: 1,
  },
  ThankYoumsgView: {
    flex: 0.95,
  },
  needHelpView: {
    flex: 0.15,
    marginTop: 48,
  },
  thankyoumsg: {
    marginLeft: 6,
    marginRight: 6,
    marginTop: 33,
    flex: 1,
  },
  allDoneText: {
    fontFamily: "Muli-Black",
    fontSize: 20,
  },
  PImsg: {
    fontSize: 16,
    fontFamily: "Muli-SemiBold",
    marginTop: 8,
  },
  needHelpText: {
    fontFamily: "Muli-ExtraBold",
    fontSize: 12,
    color: "#999999",
  },
  buttonStyle: {
    height: 40,
    marginLeft: 6,
    marginRight: 6,
    borderColor: "#444444",
    borderWidth: 1,
    borderRadius: 4,
    marginTop: 12,
    flexDirection: "row",
    alignItems: "center",
    marginBottom: 4,
  },
  buttonText: {
    fontFamily: "Muli-Bold",
    fontSize: 16,
    marginLeft: 16,
  },
});
