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,
} 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 { SCREEN_HEIGHT } from "react-native-digitcamera/lib/commonjs/common/Constants";
import { dispatch } from "react-native-digitcamera/src/common/RootNavigation";
import { ScrollView } from "react-native-gesture-handler";
import Database from "../../../../Components/common/Database";
import { async } from "validate.js";
import {
  errorRecord,
  firebaseAttributes,
} from "react-native-digitcamera/src/common/libEventLog/libCrashlytics/libCrashlyticsEvent";
let realm = Database.getRealm();

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;

const ThankYou = ({ navigation, route }) => {
  var vechicleData = realm.objects("PIVechicleData");
  toWithQuote = vechicleData[0]?.toWithQuote;
  toTutorial = vechicleData[0]?.toTutorial;
  const [thankYou, SetThankYou] = useState("All Done!");
  const [isLoading, SetIsLoading] = useState(true);
  const [message, SetMessage] = useState(
    "The pre-inspection process is completed We will update you soon with further details"
  );

  const { activityID, activityTypeId, licensePlateNumber, quoteNumber } =
    useSelector((state) => state.vechicleDetails?.vehicleInfo);
  const { sensorDataInfo } = useSelector((state) => state.sensorImageData);
  const dispatch = useDispatch();
  useEffect(() => {
    Orientation.lockToPortrait();
    console.log("route.params.props.navigation", toWithQuote, toTutorial);

    // API call
    documentLast();
    // disabled back handler
    const backHandler = BackHandler.addEventListener(
      "hardwareBackPress",
      () => {
        return true;
      }
    );

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

  // document last API call
  const documentLast = async () => {
    try {
      SetIsLoading(true);
      await genrateSensorFile(
        activityID,
        activityTypeId,
        licensePlateNumber,
        quoteNumber,
        sensorDataInfo,
        async () => {
          const DocumentLastData = await getDocumentLast({
            body: {
              activityId: activityID,
              isLast: true,
              source: "DIGITEDGE",
            },
          });
          console.log(
            "Document last Responce",
            JSON.stringify(DocumentLastData, null, "  ")
          );
          renderMsgToScreen(DocumentLastData);
        }
      );
      SetIsLoading(false);
    } catch (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",
      });
    } catch (error) {
      firebaseAttributes(error);
      errorRecord(error);
    }
  };

  const clearAllRealmData = () => {
    try {
      realm.write(() => {
        realm.delete(realm.objects("PIOfflineData"));
      });
      realm.write(() => {
        realm.delete(realm.objects("PIVechicleInstruction"));
      });
      realm.write(() => {
        realm.delete(realm.objects("PIRetryCount"));
        realm.create("PIRetryCount", {
          retryCount: 0,
          index: 0,
          isAddNewImageData: false,
        });
      });
      realm.write(() => {
        realm.delete(realm.objects("PILocation"));
      });
      realm.write(() => {
        realm.delete(realm.objects("PIStartOver"));
        realm.create("PIStartOver", {
          isStartOver: true,
        });
      });
      realm.write(() => {
        realm.delete(realm.objects("PIINDEX"));
        realm.create("PIINDEX", {
          lastIndex: 0,
        });
      });

      realm.write(() => {
        realm.delete(realm.objects("PIclickedCount"));
        realm.create("PIclickedCount", {
          clickedCount: 0,
        });
      });

      realm.write(() => {
        realm.delete(realm.objects("PIUploadedCount"));
        realm.create("PIUploadedCount", {
          uploadedCount: 0,
        });
      });
      realm.write(() => {
        realm.delete(realm.objects("PIRetryCount"));
        realm.create("PIRetryCount", {
          retryCount: 0,
          index: 0,
          isAddNewImageData: true,
        });
      });
    } catch (error) {
      errorRecord(error);
      firebaseAttributes(error);
    }
  };

  const addRealmVechicleData = () => {
    realm.write(() => {
      realm.delete(realm.objects("PICompleteStatus"));
      realm.create("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}>{translate(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
                    );
                  }
                  await 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,
  },
});
