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 {
  SCREEN_HEIGHT,
  SCREEN_WIDTH,
} from "react-native-digitcamera/lib/commonjs/common/Constants";
import { renderErrorMsge } from "react-native-digitcamera/src/common/Validation";
import { ScrollView } from "react-native-gesture-handler";
import { async } from "validate.js";
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/Database";
import { POLICY_NUMBER_REGX } 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";

let realm = Database.getRealm();
var PICompleteStatus = realm.objects("PICompleteStatus");
const iOS = Platform.OS === "ios";

const girl_selfi = require("../common/Image/girl_selfi.png");
const WithQuote = ({ navigation, route }) => {
  var vechicleData = realm.objects("PIVechicleData");
  var registrationNumber;
  const [, updateState] = React.useState();
  const forceUpdate = React.useCallback(() => updateState({}), []);
  const [quoteNumber, setQuoteNumber] = useState("");
  const [isLoading, setISsLoading] = useState(false);
  const [isPIModalVisible, setisPIModalVisible] = useState(false);
  const dispatch = useDispatch();
  const { agentEmail, agentName, agentMobile, toWithQuote, toTutorial } =
    route.params;

  var activityData;

  useEffect(() => {
    console.log("##########");
    Orientation.lockToPortrait();
    let unsubscribe = navigation.addListener("focus", () => {
      Orientation.lockToPortrait();
    });
    return () => {
      unsubscribe();
    };
  }, []);
  //to get activity id and activityTypeid
  const callGetActivityid = async () => {
    try {
      //API call
      const agentData = realm.objects("AgentDetails");
      const panHolderName = agentData[0]?.panHolderName;
      const panNo = agentData[0]?.panNo;
      const agentNumber = agentData[0]?.agentNumber;
      const body = {
        activityTypeId: 0,
        customerDetailData: {
          emailId: agentEmail,
          name: agentName,
          phoneNo: agentMobile,
          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[0].value,
          toWithQuote: toWithQuote,
          toTutorial: toTutorial,
          quoteNumber: quoteNumber,
        },
      });
      realm.write(() => {
        realm.delete(realm.objects("PIVechicleData"));
        realm.create("PIVechicleData", {
          activityId: activityData?.activityID,
          activityTypeId: activityData?.activityTypeId,
          licensePlateNumber: registrationNumber[0].value,
          toWithQuote: toWithQuote,
          toTutorial: toTutorial,
          quoteNumber: quoteNumber,
          ncb: Number(userNCB),
          vechicleType: "",
        });
      });

      realm.write(() => {
        realm.delete(realm.objects("PICompleteStatus"));
        realm.create("PICompleteStatus", {
          piStatus: false,
        });
      });
      // var RealmData = realm.objects("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(() => {
        Alert.alert(
          "Oops! Unable to proceed",
          "We are experiencing technical issue, Please try after sometime"
        );
      }, 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[0]?.piStatus == true ? null : (
          <PrimaryButton
            onPress={() => {
              realmStoreStartOver(false);
              setisPIModalVisible(false);
              navigation.navigate("Toturial", {
                activityId: activityData?.activityID,
                activityTypeId: activityData?.activityTypeId,
                licensePlateNumber: vechicleData[0]?.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 = () => {
    try {
      realm.write(() => {
        realm.delete(realm.objects("PIOfflineData"));
      });
      realm.write(() => {
        realm.delete(realm.objects("PIVechicleData"));
      });
      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("PIclickedCount"));
        realm.create("PIclickedCount", {
          clickedCount: 0,
        });
      });

      realm.write(() => {
        realm.delete(realm.objects("PIUploadedCount"));
        realm.create("PIUploadedCount", {
          uploadedCount: 0,
        });
      });
    } 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",
    });
  };

  const checkPICondition = async () => {
    try {
      if (vechicleData[0]?.quoteNumber == quoteNumber) {
        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 = (status) => {
    try {
      realm.write(() => {
        realm.delete(realm.objects("PIStartOver"));
        realm.create("PIStartOver", {
          isStartOver: status,
        });
      });
    } catch (error) {
      firebaseAttributes(error);
      errorRecord(error);
    }
  };

  const logutAndNavigate = () => {
    try {
      realm.write(() => {
        realm.delete(realm.objects("AppLoginStatus"));
        realm.create("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: () => {
          logutAndNavigate();
        },
        style: "cancel",
      },
      {
        text: "No",
        onPress: () => {
          console.log("on No pressed");
        },
      },
    ]);
  };

  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}>
          <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={() => {
                logoutAlertModal();
              }}
            />
            {/* Image view */}
            <View style={styles.imageView}>
              <Image
                source={girl_selfi}
                style={{
                  resizeMode: "contain",
                  width: "100%",
                  height: (SCREEN_HEIGHT * 25) / 100,
                }}
              />
            </View>
            {/* Text View */}
            <View style={styles.textView}>
              <Text style={styles.welcomeText}>{translate("Welcome!")}</Text>
              <Text style={styles.subText}>
                {translate(
                  "Our pre-inspection process is super simple and quick All you need to do is upload images of the vehicle by following instructions"
                )}
              </Text>

              <TextInput
                autoCapitalize="characters"
                label={translate("Enter Quote/Policy number")}
                // value={odometerReadings}
                onChangeText={(value) => {
                  setQuoteNumber(value);
                }}
                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={() => {
                  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={() => {
                  navigation.navigate("WithoutQuoteScreen");
                  firebaseEvents(
                    "dont_have_quote_number",
                    { quoteNumber: quoteNumber },
                    activityData?.activityID,
                    activityData?.activityTypeId,
                    ""
                  );
                }}
              ></RoundButton>
            </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,
  },
});
