import {
  Alert,
  Image,
  StyleSheet,
  Text,
  View,
  KeyboardAvoidingView,
  BackHandler,
  Platform,
} from "react-native";
import React, { useEffect, useRef, useState } from "react";
import Header from "../Screens/Header";
import { translate } from "react-native-digitcamera/src/common/localize/i18n";
import Orientation from "../../../react-native-orientation";
import {
  TextInput,
  PrimaryButton,
  RoundButton,
  Spinner,
} from "../common/ThemedComponents";
import { renderErrorMsge } from "react-native-digitcamera/src/common/Validation";
import { ScrollView } from "react-native-gesture-handler";

import { getActivityid } from "react-native-digitcamera/src/common/Services/getActivityid";
import { useDispatch } from "react-redux";
import Modal from "../common/Modal";
import Database from "../../../../Components/common/DAsyncStorage";
import {
  POLICY_NUMBER_REGX,
  SCREEN_HEIGHT,
  SCREEN_WIDTH,
} from "react-native-digitcamera/src/common/Constants";
import {
  firebaseAttributes,
  errorRecord,
  firebaseEvents,
} from "../common/libEventLog/libCrashlytics/libCrashlyticsEvent";
import analytics from "@react-native-firebase/analytics";
import Colors from "react-native-digitcamera/src/common/Colors";
import Icon from "react-native-vector-icons/MaterialCommunityIcons";
import MIcon from "react-native-vector-icons/MaterialIcons";

import {
  UELogEvent,
  UELogMessage,
} from "../common/libEventLog/UserExperior/LibUserExperior";
import style from "../../../../Components/common/CommonStyle";
import ImagePlaceholder from "react-native-digitcamera/src/common/ImagePlaceholder";

var PICompleteStatus;
var vechicleData;
const iOS = Platform.OS === "ios";

const girl_selfi = require("../common/Image/girl_selfi.png");
const WithQuote = ({ navigation, route }) => {
  const [quoteNumber, setQuoteNumber] = useState("");
  const [isLoading, setISsLoading] = useState(false);
  const [isPIModalVisible, setisPIModalVisible] = useState(false);
  const [, updateState] = React.useState();
  const forceUpdate = React.useCallback(() => updateState({}), []);

  var registrationNumber;
  const [wrongQuoteModalVisible, setWrongQuoteModalVisible] = useState(false);
  const dispatch = useDispatch();
  const { agentEmail, agentName, agentMobile, toWithQuote, toTutorial } =
    route.params;

  var activityData;
  var instruction;

  useEffect(async () => {
    if (!iOS) {
      const Immersive = require("react-native-immersive").Immersive;
      Immersive.setImmersive(false);
    }
    Orientation.lockToPortrait();

    PICompleteStatus = await Database.get("PICompleteStatus");
    vechicleData = await Database.get("PIVechicleData");
    var isFromLink = await Database.get("PIDeeplink").isFromLink;
    instruction = await Database.get("PIVechicleInstruction");
    if (isFromLink) {
      navigation.navigate("Toturial");
    }

    let unsubscribe = navigation.addListener("focus", () => {
      if (!iOS) {
        const Immersive = require("react-native-immersive").Immersive;
        Immersive.setImmersive(false);
      }

      // this flow will excute only when app is not loging and user come through otp validation screen
      // if user come through the link then we are storing the flag in APP's App.js from their according to flag we are navigating to the screen
      if (isFromLink) {
        navigation.navigate("Toturial");
      }
      Orientation.lockToPortrait();
    });

    return () => {
      unsubscribe();
    };
  }, []);
  //to get activity id and activityTypeid
  const callGetActivityid = async () => {
    try {
      /* wrong quote number modal */
      if (quoteNumber.match(POLICY_NUMBER_REGX) == null) {
        if (!wrongQuoteModalVisible) {
          setWrongQuoteModalVisible(true);
          setISsLoading(false);
          return;
        }
      }
      //API call
      const { getUserDetails } = require("../common/Who");
      console.log("*** callGetActivityid before getUserDetails");
      await getUserDetails();
      console.log("*** callGetActivityid after getUserDetails");
      const {
        emailId,
        name,
        phoneNo,
        panHolderName,
        panNo,
        agentNumber,
      } = require("../common/Who");
      console.log("*** callGetActivityid after getUserDetails name: " + name);

      const AppLoginStatus = await Database.get("AppLoginStatus");
      const USERTYPE = AppLoginStatus?.userType;
      let body;
      if (USERTYPE === "Customer") {
        body = {
          activityTypeId: "0",
          customerDetailData: {
            emailId: emailId,
            name: name,
            phoneNo: phoneNo,
          },
          licensePlateNumber: "",
          previousPolicyExpired: true,
          quoteNumber: quoteNumber,
        };
      } else if (USERTYPE === "DealerOrAgent") {
        body = {
          activityTypeId: "0",
          customerDetailData: {
            emailId: emailId,
            name: name,
            phoneNo: phoneNo,
            panHolderName: panHolderName,
            panNo: panNo,
          },
          agentId: agentNumber,
          licensePlateNumber: "",
          previousPolicyExpired: true,
          quoteNumber: quoteNumber,
        };
      }

      activityData = await getActivityid({ body });

      registrationNumber = activityData?.additionalActivitiesList.filter(
        (item) => {
          if (item.key == "Registration Number") {
            return item;
          }
        }
      );
      let userNCB = activityData?.additionalActivitiesList.filter((item) => {
        if (item.key == "User NCB") {
          return item;
        }
      });
      setISsLoading(false); // adding data to redux
      dispatch({
        type: "ACTIVITY_DATA",
        payload: {
          activityId: activityData?.activityID,
          activityTypeId: activityData?.activityTypeId,
          licensePlateNumber:
            registrationNumber === undefined ? "" : registrationNumber[0].value,
          toWithQuote: toWithQuote,
          toTutorial: toTutorial,
          quoteNumber: quoteNumber,
        },
      });
      await Database.update("PIVechicleData", {
        activityId: activityData?.activityID,
        activityTypeId: activityData?.activityTypeId,
        licensePlateNumber:
          registrationNumber === undefined ? "" : registrationNumber[0].value,
        toWithQuote: toWithQuote,
        toTutorial: toTutorial,
        quoteNumber: quoteNumber,
        ncb:
          userNCB === undefined || userNCB.length == 0
            ? 0
            : Number(userNCB[0].value),
        vechicleType: "",
      });
      await Database.update("PICompleteStatus", {
        piStatus: false,
      });
      // var RealmData = Database.get("PIVechicleData"); // console.log("&&&&&&&&& ",RealmData);

      navigation.navigate("Toturial", {
        activityId: activityData?.activityID,
        activityTypeId: activityData?.activityTypeId,
        licensePlateNumber: registrationNumber[0]?.value,
      });
    } catch (error) {
      firebaseAttributes(error);
      errorRecord(error);
      console.log("IN WithQuote => error in service ", error);
      setTimeout(() => {
        if (!wrongQuoteModalVisible) {
          setWrongQuoteModalVisible(true);
        }
        //   Alert.alert(
        //     "Oops! Unable to proceed",
        //     "We are experiencing technical issue, Please try after sometime. Or Still You can continue with registration number",
        //     [
        //       {
        //         text: "Cancel",
        //         onPress: () => { },
        //         style: "cancel",
        //       },
        //       {
        //         text: "Continue",
        //         onPress: () => {
        //           navigation.navigate("WithoutQuoteScreen");
        //         },
        //       },
        //     ]
        //   );
      }, 100);
      setISsLoading(false);
    }
  };

  const PreinspectionAlertUx = () => {
    return (
      <View style={{ marginLeft: 16, marginRight: 16 }}>
        <Text
          style={{
            fontSize: 14,
            fontFamily: "Muli-Regular",
            marginBottom: 16,
            lineHeight: 22,
            marginTop: SCREEN_WIDTH / 10,
          }}
        >
          {translate(
            "It seems like you are already in middle of a pre-inspection process You can either continue from where you left off or start from begining"
          )}
        </Text>
        {PICompleteStatus?.piStatus == true ? null : (
          <PrimaryButton
            onPress={() => {
              realmStoreStartOver(false);
              setisPIModalVisible(false);
              navigation.navigate("Toturial", {
                activityId: activityData?.activityID,
                activityTypeId: activityData?.activityTypeId,
                licensePlateNumber: vechicleData?.licensePlateNumber,
              });
              firebaseEvents(
                "Continue_Existing_Flow",
                { quoteNumber: quoteNumber },
                activityData?.activityID,
                activityData?.activityTypeId,
                ""
              );
            }}
          >
            {translate("Continue")}
          </PrimaryButton>
        )}

        <PrimaryButton
          onPress={async () => {
            setisPIModalVisible(false),
              setISsLoading(true),
              await clearAllRealmData(),
              await clearRedux();
            realmStoreStartOver(true);
            callGetActivityid();
            firebaseEvents(
              "Start_Over_New_Flow",
              { quoteNumber: quoteNumber },
              activityData?.activityID,
              activityData?.activityTypeId,
              ""
            );
          }}
          style={{
            backgroundColor: "#FFFFFF",
            borderWidth: 1,
            marginTop: 16,
            marginBottom: SCREEN_WIDTH / 10,
          }}
        >
          {translate("Start Over")}
        </PrimaryButton>
      </View>
    );
  };

  const preInspectionAlert = () => {
    return (
      <View>
        <Modal
          isVisible={isPIModalVisible}
          onBackdropPress={() => setisPIModalVisible(false)}
          onClose={() => isPIModalVisible}
          heading={"Preinspection Alert!"}
          isTranslate={true}
          headerImageVisible={false}
        >
          {PreinspectionAlertUx()}
        </Modal>
      </View>
    );
  };

  const clearAllRealmData = async () => {
    try {
      await Database.remove("PIOfflineData");
      await Database.remove("PIVechicleData");
      await Database.remove("PIVechicleInstruction");
      await Database.update("PIGonePoseDetection", {
        GoneposeDetectionCount: 0,
      });

      await Database.update("PIPoseDetectionCompleted", {
        poseDetectionCompletedCount: 0,
      });
      await Database.update("PIRetryCount", {
        retryCount: 0,
        index: 0,
        isAddNewImageData: false,
      });

      await Database.update("PIclickedCount", {
        clickedCount: 0,
      });

      await Database.update("PIUploadedCount", {
        uploadedCount: 0,
      });
      await Database.remove("PIMediaStatus");
    } catch (error) {
      firebaseAttributes(error);
      errorRecord(error);
    }
  };

  const clearRedux = () => {
    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",
    });
  };

  const checkPICondition = async () => {
    try {
      if (vechicleData?.quoteNumber == quoteNumber && false) {
        // false indicates it will not ask "Continue" option if previously any pre-inspection done
        setisPIModalVisible(true);
      } else {
        setisPIModalVisible(false);
        setISsLoading(true);
        await clearAllRealmData();
        await clearRedux();
        callGetActivityid();
        firebaseEvents(
          "Continue_New_Flow",
          { quoteNumber: quoteNumber },
          activityData?.activityID,
          activityData?.activityTypeId,
          ""
        );
      }
    } catch (error) {
      firebaseAttributes(error);
      errorRecord(error);
    }
  };

  const realmStoreStartOver = async (status) => {
    try {
      await Database.update("PIStartOver", {
        isStartOver: status,
      });
    } catch (error) {
      firebaseAttributes(error);
      errorRecord(error);
    }
  };

  const logutAndNavigate = async () => {
    try {
      await Database.update("AppLoginStatus", {
        userType: "Customer",
        isAppLoging: false,
      });
      route.params.props.navigation.navigate("CustomerDetails");
    } catch (error) {
      firebaseAttributes(error);
      errorRecord(error);
      console.log("Error : ", error);
    }
  };

  const logoutAlertModal = () => {
    Alert.alert("Logout", "Are you sure?", [
      {
        text: "Yes",
        onPress: () => {
          UELogEvent("Pressed Yes in Logout Modal", {
            "Quote Value": quoteNumber,
          });
          logutAndNavigate();
        },
        style: "cancel",
      },
      {
        text: "No",
        onPress: () => {
          UELogEvent("Pressed No in Logout Modal", {
            "Quote Value": quoteNumber,
          });
          console.log("on No pressed");
        },
      },
    ]);
  };

  /* Quote failed modal */

  const wrongQuoteNumberModal = () => {
    return (
      <Modal
        isVisible={wrongQuoteModalVisible}
        headerImageVisible={false}
        shouldHeaderVisible={false}
      >
        <View
          style={{
            height: SCREEN_HEIGHT * 0.65,
            flex: 1,
            paddingHorizontal: 16,
            paddingBottom: 16,
            justifyContent: "space-between",
          }}
        >
          <View
            key={"ModalHeader"}
            style={{
              flex: 0.1,
              flexDirection: "row",
              justifyContent: "space-between",
              alignItems: "center",
            }}
          >
            <Text style={[style.muliBoldDB, { fontSize: 18 }]}>OOPS</Text>
            <Icon
              name="close"
              size={24}
              color={Colors.veryLightGray}
              onPress={() => {
                setWrongQuoteModalVisible(false);
              }}
            />
          </View>

          <View style={{ flex: 0.65 }}>
            <Image
              source={{
                uri: "https://d2h44aw7l5xdvz.cloudfront.net/CRM/PRM/oops_something_went_wrong.png",
              }}
              style={styles.wrong}
            />
            <Text style={[style.muliRegDB, { fontSize: 16, marginTop: 24 }]}>
              Looks like you made a mistake entering your policy/quote number.
            </Text>
          </View>

          <View style={{ flex: 0.25, justifyContent: "space-evenly" }}>
            <PrimaryButton
              onPress={() => {
                setWrongQuoteModalVisible(false);
              }}
            >
              Try Again
            </PrimaryButton>
            <PrimaryButton
              onPress={() => {
                setWrongQuoteModalVisible(false),
                  navigation.navigate("WithoutQuoteScreen");
              }}
              mode={"outlined"}
            >
              I don't know my policy/quote no.
            </PrimaryButton>
          </View>
        </View>
      </Modal>
    );
  };

  return (
    <KeyboardAvoidingView
      style={{ flex: 1, backgroundColor: Colors.white }}
      behavior={iOS ? "padding" : ""}
      enabled
    >
      <ScrollView
        style={{ flex: 1, backgroundColor: Colors.white }}
        keyboardShouldPersistTaps={iOS ? "always" : "handled"}
        keyboardDismissMode="on-drag"
      >
        <View style={styles.main}>
          {/* <StencilAnimation/> */}
          <Spinner loading={isLoading} />
          <View style={styles.subView}>
            <Header
              hideArrowBackButton={iOS ? true : false}
              onlanguagechange={() => {
                forceUpdate();
              }}
              onbackPress={() => {
                //call exit alert
                if (Platform.OS === "android") {
                  Alert.alert("Exit Application", "Are you sure?", [
                    {
                      text: "Yes",
                      onPress: () => {
                        BackHandler.exitApp();
                      },
                      style: "cancel",
                    },
                    {
                      text: "No",
                      onPress: () => {
                        console.log("on No pressed");
                      },
                    },
                  ]);
                }

                //   if (toWithQuote) {
                //     if (toTutorial) {
                //       route.params.props.navigation.navigate(
                //         route?.params?.navigateBackToManualPI
                //       );
                //     } else {
                //       route.params.props.navigation.navigate(
                //         route?.params?.navigateBackTo
                //       );
                //     }
                //   } else {
                //     route.params.props.navigation.navigate(
                //       route?.params?.navigateBackToPostplanPreviousPolicy
                //     );
                //   }
                // }}
              }}
              isLogoutVisible={true}
              onLogoutPress={() => {
                UELogEvent("Logout Pressed", {
                  "Message Shown": "Are you sure",
                });

                logoutAlertModal();
              }}
            />
            {/* Image view */}
            <View style={styles.imageView}>
              <Image
                source={girl_selfi}
                style={{
                  resizeMode: "contain",
                  width: "100%",
                  height: (SCREEN_HEIGHT * 20) / 100,
                }}
              />
            </View>
            {/* Text View */}
            <View style={styles.textView}>
              <Text style={styles.welcomeText}>{translate("Welcome!")}</Text>
              <Text style={styles.subText}>
                {
                  "Our pre-inspection process will only take few minutes. All you need to do is upload a video/images of your car. \n\nDon’t worry, we’ll be with you every step of the way!"
                }
              </Text>

              <TextInput
                autoCapitalize="characters"
                label={translate("Enter Quote/Policy number")}
                // value={odometerReadings}
                onChangeText={(value) => {
                  setQuoteNumber(value.trim());
                }}
                errorMsge={
                  quoteNumber.match(POLICY_NUMBER_REGX) == null
                    ? renderErrorMsge({
                        type: "input",
                        text: "quote / policy number",
                      })
                    : null
                }
              />
            </View>
            {preInspectionAlert()}
            {/* Button view */}
            <View style={styles.buttonView}>
              <PrimaryButton
                disabled={quoteNumber.length > 0 ? false : true}
                style={{ marginTop: 24 }}
                onPress={() => {
                  UELogEvent("Clicked on continue", {
                    "Button Title": "Continue",
                    quoteNumber: quoteNumber,
                  });
                  realmStoreStartOver(true);
                  checkPICondition();
                }}
              >
                {translate("Continue")}
              </PrimaryButton>
              <RoundButton
                style={{
                  height: 50,
                  borderColor: "#DDDDDD",
                  borderWidth: 1,
                  borderRadius: 16,
                  marginTop: 18,
                  width: SCREEN_WIDTH - 108,
                  alignSelf: "center",
                  justifyContent: "center",
                  marginBottom: 20,
                }}
                Title={translate("Don’t have Quote/Policy No?")}
                onClicked={() => {
                  console.log(
                    "**************************** withQuote onClicked"
                  );
                  UELogEvent("Clicked on dont have quote number", {
                    "Button Title": "Don’t have Quote/Policy No?",
                  });
                  navigation.navigate("WithoutQuoteScreen"); // **&&&
                  // navigation.navigate("Camera", {
                  //   activityId: "",
                  //   activityTypeId: 5,
                  //   licensePlateNumber: "MH09BM7812",
                  //   toVDO: true /* @NEWORDER */,
                  //   instruction: JSON.stringify(instruction),
                  // });
                  firebaseEvents(
                    "dont_have_quote_number",
                    { quoteNumber: quoteNumber },
                    activityData?.activityID,
                    activityData?.activityTypeId,
                    ""
                  );
                }}
              ></RoundButton>
              {wrongQuoteNumberModal()}
            </View>
          </View>
        </View>
      </ScrollView>
    </KeyboardAvoidingView>
  );
};
export default WithQuote;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "flex-end",
  },
  main: {
    flex: 1,
    backgroundColor: "#FFFFFF",
  },
  imageView: {
    flex: 0.4,
    justifyContent: "center",
    alignItems: "center",
    marginTop: 50,
  },
  textView: {
    flex: 0.45,
  },
  buttonView: {
    flex: 0.15,
  },
  welcomeText: {
    fontSize: 18,
    fontFamily: "Muli-ExtraBold",
    marginBottom: 9,
    marginTop: 52,
  },
  subText: {
    fontFamily: "Muli-Regular",
    fontSize: 14,
    marginBottom: 23,
  },
  subView: {
    flex: 1,
    marginLeft: 24,
    marginRight: 24,
  },
  wrong: {
    height: "50%",
    width: "50%",
    resizeMode: "contain",
    alignSelf: "center",
  },
});
