import {
  Alert,
  Image,
  ScrollView,
  StyleSheet,
  Text,
  View,
  BackHandler,
} from "react-native";
import React, { useEffect, useRef, useState } from "react";
import Header from "react-native-digitcamera/src/Screens/Header";
import SqureRadio from "react-native-digitcamera/src/common/SqureRadio";
import { translate } from "react-native-digitcamera/src/common/localize/i18n";
import {
  TextInput,
  PrimaryButton,
  RoundButton,
  Spinner,
} from "react-native-digitcamera/src/common/ThemedComponents";
import { SCREEN_WIDTH } from "react-native-digitcamera/lib/commonjs/common/Constants";
import ProductCard from "react-native-digitcamera/src/common/ProductCard";
import Colors from "react-native-digitcamera/lib/commonjs/common/Colors";
import { renderErrorMsge } from "react-native-digitcamera/src/common/Validation";
import { getActivityid } from "react-native-digitcamera/src/common/Services/getActivityid";
import reactotron from "reactotron-react-native";
import { useDispatch } from "react-redux";
import Database from "../../../../Components/common/Database";
import Modal from "react-native-digitcamera/src/common/Modal";
import Orientation from "react-native-orientation";
import { async } from "validate.js";
import {
  REGISTRATION_NUMBER_REGX,
  SCREEN_HEIGHT,
} from "react-native-digitcamera/src/common/Constants";
import {
  errorRecord,
  firebaseAttributes,
  firebaseEvents,
} from "../common/libEventLog/libCrashlytics/libCrashlyticsEvent";

let realm = Database.getRealm();
const girl_selfi = require("../common/Image/girl_selfi.png");
const car = require("../common/Image/car.png");
const Bike = require("../common/Image/Bike.png");
const cummercial = require("../common/Image/cummercial.png");
var vechicleData = realm.objects("PIVechicleData");
var PICompleteStatus = realm.objects("PICompleteStatus");

const NCB_SLABS = [
  { ncb: 0, name: "0%", id: 1, value: "ZERO" },
  { ncb: 20, name: "20%", id: 2, value: "TWENTY" },
  { ncb: 25, name: "25%", id: 3, value: "TWENTY_FIVE" },
  { ncb: 35, name: "35%", id: 4, value: "THIRTY_FIVE" },
  { ncb: 45, name: "45%", id: 5, value: "FORTY_FIVE" },
  { ncb: 50, name: "50%", id: 6, value: "FIFTY" },
].reverse();

const WithoutQuoteScreen = ({ navigation, route }) => {
  const [, updateState] = React.useState();
  const forceUpdate = React.useCallback(() => updateState({}), []);
  const [_4Wclicked, set4wclicked] = useState(false);
  const [_2Wclicked, set2wclicked] = useState(false);
  const [cvclicked, setCVclicked] = useState(false);
  const [ncbDisabled, setncbDisabled] = useState(false);
  const [selectedNCB, setselectedNCB] = useState("");
  const [isVechicleTypeSelected, setIsVechicleTypeSelected] = useState(false);
  const [registrationNumber, setRegistrationNumber] = useState("");
  const [activityTypeId, setActivityTypeId] = useState(null);
  const [isLoading, setISsLoading] = useState(false);
  const [isPIModalVisible, setisPIModalVisible] = useState(false);
  const [vechicleType, setVechicleType] = useState("");

  const dispatch = useDispatch();

  useEffect(() => {
    Orientation.lockToPortrait();
    let unsubscribe = navigation.addListener("focus", () => {
      Orientation.lockToPortrait();
    });
    return () => {
      unsubscribe();
    };
  }, []);
  const { agentEmail, agentName, agentMobile, toWithQuote, toTutorial } =
    route.params;

  var activityData;

  //to get activity id and activityTypeid
  const callGetActivityid = async () => {
    try {
      const agentData = realm.objects("AgentDetails");
      const panHolderName = agentData[0]?.panHolderName;
      const panNo = agentData[0]?.panNo;
      const agentNumber = agentData[0]?.agentNumber;
      const body = {
        activityTypeId: activityTypeId,
        customerDetailData: {
          emailId: agentEmail,
          name: agentName,
          phoneNo: agentMobile,
          panHolderName: panHolderName,
          panNo: panNo,
        },
        agentId: agentNumber,
        licensePlateNumber: registrationNumber,
        previousPolicyExpired: true,
        quoteNumber: "",
        usrNcb: selectedNCB?.ncb,
      };
      activityData = await getActivityid({ body });
      // added data in redux
      dispatch({
        type: "ACTIVITY_DATA",
        payload: {
          activityId: activityData?.activityID,
          activityTypeId: activityTypeId,
          licensePlateNumber: registrationNumber,
          toWithQuote: true,
          quoteNumber: "",
        },
      });
      realm.write(() => {
        console.log(
          "activityData?.activityTypeId",
          activityData?.activityTypeId
        );
        realm.delete(realm.objects("PIVechicleData"));
        realm.create("PIVechicleData", {
          activityId: activityData?.activityID,
          activityTypeId: activityData?.activityTypeId,
          licensePlateNumber: registrationNumber,
          toWithQuote: toWithQuote,
          toTutorial: toTutorial,
          quoteNumber: "",
          ncb: selectedNCB?.ncb,
          vechicleType: vechicleType,
        });
      });

      realm.write(() => {
        realm.delete(realm.objects("PICompleteStatus"));
        realm.create("PICompleteStatus", {
          piStatus: false,
        });
      });

      setISsLoading(false);
      navigation.navigate("Toturial");
    } catch (error) {
      firebaseAttributes(error);
      errorRecord(error);
      console.log("@@@@@@@@@@@@", error);
      setTimeout(() => {
        Alert.alert(
          "Oops! Unable to proceed",
          "We are experiencing technical issue, Please try after sometime"
        );
      }, 100);
      setISsLoading(false);
    }
  };
  const PreinspectionAlertUx = () => {
    return (
      <ScrollView>
        <View style={{ marginLeft: 16, marginRight: 16 }}>
          <Text
            style={{
              fontSize: 14,
              fontFamily: "Muli-Regular",
              marginBottom: 16,
              lineHeight: 22,
              marginTop: SCREEN_HEIGHT / 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>
          {console.log("vechicleData?.piStatus", vechicleData[0]?.piStatus)}
          {PICompleteStatus[0]?.piStatus == true ? null : (
            <PrimaryButton
              onPress={async () => {
                firebaseEvents(
                  "Continue_Existing_Flow",
                  {
                    registrationNumber: registrationNumber,
                    vechicleType: vechicleType,
                    ncb: selectedNCB?.ncb,
                  },
                  activityData?.activityID,
                  activityTypeId,
                  ""
                );
                await realmStoreStartOver(false);
                setisPIModalVisible(false);
                navigation.navigate("Toturial");
              }}
            >
              {translate("Continue")}
            </PrimaryButton>
          )}

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

  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("PICompleteStatus"));
      });
      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 = () => {
    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 checkPICondition = async () => {
    console.log(
      "*****************",
      vechicleData[0]?.licensePlateNumber,
      registrationNumber
    );
    if (
      vechicleData[0]?.licensePlateNumber == registrationNumber &&
      vechicleData[0]?.ncb == selectedNCB?.ncb &&
      vechicleData[0]?.vechicleType == vechicleType
    ) {
      console.log("))))))))))))))))))))))))))))))))))))))))", selectedNCB?.ncb);
      setisPIModalVisible(true);
    } else {
      firebaseEvents(
        "Continue_New_Flow",
        {
          registrationNumber: registrationNumber,
          vechicleType: vechicleType,
          ncb: selectedNCB?.ncb,
        },
        activityData?.activityID,
        activityTypeId,
        ""
      );
      setISsLoading(true);
      setisPIModalVisible(false);
      await clearAllRealmData();
      await clearRedux();
      callGetActivityid();
    }
  };

  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,
        });
      });
      navigation.navigate("CustomerDetails");
    } catch (error) {
      firebaseAttributes(error);
      console.log(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 (
    <View style={styles.main}>
      <ScrollView>
        <Spinner loading={isLoading} />
        <View style={styles.subView}>
          <Header
            hideArrowBackButton={false}
            onlanguagechange={() => {
              forceUpdate();
            }}
            onbackPress={() => {
              navigation.goBack();
            }}
            isLogoutVisible={true}
            onLogoutPress={() => {
              logoutAlertModal();
            }}
          />
          {/* Image view */}
          <View style={styles.imageView}>
            <Text style={styles.subHeaderText}>
              {translate("Choose vehicle type")}
            </Text>

            <View style={{ flexDirection: "row" }}>
              {/* 4 W */}
              <ProductCard
                imageSource={car}
                title={translate("4 wheeler")}
                key={"4 wheeler"}
                onPress={() => {
                  set4wclicked(true);
                  set2wclicked(false);
                  setCVclicked(false);
                  setIsVechicleTypeSelected(true);
                  setActivityTypeId(5);
                  setVechicleType("FourWheller");
                }}
                style={{
                  marginLeft: 8,
                  marginBottom: 16,
                  width: (SCREEN_WIDTH - 100) / 3,
                  borderColor: _4Wclicked
                    ? Colors.digitYellow
                    : Colors.greyBlack,
                  borderWidth: 1,
                  borderRadius: 4,
                  backgroundColor: "white",
                  marginRight: 8,
                }}
              />

              {/* 2 W */}
              <ProductCard
                imageSource={Bike}
                title={translate("2 wheeler")}
                key={"2 wheeler"}
                onPress={() => {
                  set4wclicked(false);
                  set2wclicked(true);
                  setCVclicked(false);
                  setIsVechicleTypeSelected(true);
                  setActivityTypeId(26);
                  setVechicleType("TwoWheeler");
                }}
                style={{
                  marginLeft: 8,
                  marginBottom: 16,
                  width: (SCREEN_WIDTH - 100) / 3,
                  borderColor: _2Wclicked
                    ? Colors.digitYellow
                    : Colors.greyBlack,
                  borderWidth: 1,
                  borderRadius: 4,
                  backgroundColor: "white",
                  marginRight: 8,
                }}
              />

              {/* cummercial */}
              <ProductCard
                imageSource={cummercial}
                title={translate("Commercial")}
                key={"Commercial"}
                onPress={() => {
                  set4wclicked(false);
                  set2wclicked(false);
                  setCVclicked(true);
                  setIsVechicleTypeSelected(true);
                  setActivityTypeId(30);
                  setVechicleType("Commercial");
                }}
                style={{
                  marginLeft: 8,
                  marginBottom: 16,
                  width: (SCREEN_WIDTH - 100) / 3,
                  borderColor: cvclicked
                    ? Colors.digitYellow
                    : Colors.greyBlack,
                  borderWidth: 1,
                  borderRadius: 4,
                  backgroundColor: "white",
                  marginRight: 8,
                }}
              />
            </View>
            {!isVechicleTypeSelected ? (
              <Text style={{ color: "red", marginLeft: 8 }}>
                {translate("Select Vechicle Type")}
              </Text>
            ) : null}
            <TextInput
              autoCapitalize="characters"
              style={{ marginLeft: 8, marginRight: 8, marginTop: 23 }}
              onChangeText={(value) => {
                setRegistrationNumber(value);
              }}
              label={translate("Enter Vehicle Reg No")}
              maxLength={11}
              errorMsge={
                registrationNumber.match(REGISTRATION_NUMBER_REGX) == null
                  ? renderErrorMsge({
                      type: "input",
                      text: "Registration Number",
                    })
                  : null
              }
            />
          </View>
          <View
            style={{
              width: SCREEN_WIDTH - 48,
              height: 1,
              borderRightWidth: 1,
              borderColor: "#F5F5F5",
              backgroundColor: "#F5F5F5",
            }}
          />
          {/* Text View */}
          <View style={styles.textView}>
            <Text style={styles.ncbHeading}>
              {translate("Select NCB percentage")}
            </Text>
            <SqureRadio
              data={NCB_SLABS}
              numberOfRecord={3}
              disabled={ncbDisabled}
              isFullValue={true}
              selected={(value) => {
                setselectedNCB(value);
              }}
              selectedvalue={selectedNCB.id}
              style={{ marginVertical: 20 }}
              noTranslation={true}
            />
            {selectedNCB.id ? null : (
              <Text style={{ color: "red" }}>
                {translate("Please select NCB")}
              </Text>
            )}
          </View>
          {preInspectionAlert()}
          {/* Button view */}
          <View style={styles.buttonView}>
            <PrimaryButton
              style={{ marginTop: 24 }}
              disabled={
                isVechicleTypeSelected &&
                registrationNumber.length >= 9 &&
                selectedNCB.id
                  ? false
                  : true
              }
              onPress={async () => {
                await 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("I have Quote/Policy No")}
              onClicked={() => {
                navigation.navigate("WithQuote");
              }}
            ></RoundButton>
          </View>
        </View>
      </ScrollView>
    </View>
  );
};
export default WithoutQuoteScreen;

const styles = StyleSheet.create({
  main: {
    flex: 1,
    backgroundColor: "#FFFFFF",
  },
  imageView: {
    flex: 0.3,
    marginTop: 36,
  },
  textView: {
    flex: 0.55,
    marginLeft: 8,
  },
  buttonView: {
    flex: 0.15,
    marginLeft: 8,
  },
  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,
  },
  subHeaderText: {
    fontSize: 16,
    fontFamily: "Muli-Bold",
    marginLeft: 8,
    marginBottom: 12,
  },
  ncbHeading: {
    fontFamily: "Muli-Bold",
    fontSize: 16,
    marginTop: 18,
    marginBottom: 12,
  },
});
