import {
  faArrowLeft,
  faEye,
  faEyeSlash,
} from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-native-fontawesome";
import { useNavigation } from "@react-navigation/native";
import React, { useEffect, useState } from "react";
import {
  StyleSheet,
  Text,
  TextInput,
  TouchableOpacity,
  View,
} from "react-native";
import {
  get_user_token,
  register_user,
  user_login,
} from "../../services/api/controllers/auth";
import {
  create_customer,
  get_customer_login_id,
  search_customer,
} from "../../services/api/controllers/customers";
import OTPAuth from "./OTP";
import AsyncStorage from "@react-native-async-storage/async-storage";
import { useToast } from "react-native-toast-notifications";
// import CryptoJS from 'crypto-js'
// import crypto from 'react-native-crypto';

const Login = () => {
  const navigation = useNavigation();
  const [status, setstatus] = useState("register");
  const [email, setemail] = useState("");
  const [error, seterror] = useState("");
  const [uid, setuid] = useState("");
  const toast = useToast();

  const [token, settoken] = useState("");
  const [tokenHere, settokenHere] = useState("");
  const [loading, setloading] = useState("");
  const [loggedIn, setloggedIn] = useState(false);
  const [seePassword, setSeePassword] = useState(false);

  const [emailDupe, setemailDupe] = useState(false);

  const [password, setpassword] = useState("");

  useEffect(() => {
    /* ---------------Check for the user saved email--------------- */

    AsyncStorage.getItem("AccessToken")
      .then((pass) => {
        console.log(pass);
        pass !== null ? navigation.navigate("Home") : null;
      })
      .catch((error) => {
        console.log(error + "weeewwww");
      });
  }, []);
  const handleLogin = (e) => {
    /* ---------------Login Function --------------- */
    user_login({
      username: email.replace(/\s/g, "").toLowerCase(),
      password: password,
    })
      .then((result) => {
        if (result.status == 200) {
          //   setuserEmail(result.data.user.email);
          //   settoken(result.data.token);
          //   setuid(result.data.user._id);
          // send_email();
          settoken(result.data.token);
          settokenHere(result.data.token);
          AsyncStorage.setItem("AccessToken", result.data.token);
          AsyncStorage.setItem("email", email.replace(/\s/g, "").toLowerCase());
          AsyncStorage.setItem("something", password);
          get_user_token({
            token: result.data.token,
          })
            .then((results) => {
              if (results.status == 200) {
                setuid(results.data.profile.userId);
                AsyncStorage.setItem("userId", results.data.profile.userId);
                get_customer_login_id({
                  id: results.data.profile.userId,
                })
                  .then((result1) => {
                    // console.log(result1.data);

                    if (result1.error) {
                      seterror(result1.error);
                    } else {
                      AsyncStorage.setItem(
                        "userData",
                        JSON.stringify(result1.data)
                      );
                      navigation.navigate("Home", { userLoggedin: true });
                    }
                  })
                  .catch((error) => {
                    // setError(error.message);
                    console.log(error.message);
                  })
                  .finally(() => {
                    // setprodIsLoading(false); // Set loading to false when done loading
                  });
              } else {
                // seterror(results.message);
                console.log("login error" + results);
              }
            })
            .catch((err) => {
              seterror(err);
              console.log(err);
              console.log(err + "failed to login");
            });
          //   setauth(true);
          console.log("login success " + result.data.token);
        } else {
          seterror(result.message);
          toast.show("Invalid Credentials!", {
            type: "danger",
            placement: "top",
            duration: 4000,
            offset: 30,
            animationType: "slide-in",
          });
          console.log("login error" + result);
        }
      })
      .catch((err) => {
        seterror(err);
        console.log(err);
        console.log(err + "failed to login");
      });
  };
  const handleChange = (e) => {
    search_customer({
      searchData: e,
    })
      .then((result) => {
        // console.log(result.data);

        if (result.error) {
          seterror(result.error);
        } else {
          if (result.data?.results.length < 1) {
            setemailDupe(false);
          } else {
            setemail(e);
            setemailDupe(true);
            console.log(result.data?.results.length + " " + emailDupe);
          }
          // console.log("length on search " + result.data?.results.length);

          setloading(false);
        }
      })
      .catch((error) => {
        // setError(error.message);
        console.log(error.message);
      })
      .finally(() => {
        // setprodIsLoading(false); // Set loading to false when done loading
      });
  };

  return (
    <View style={styles.container}>
      {/* <View style={styles.header}> */}
      {/* <TouchableOpacity
          onPress={() => navigation.navigate("Home")}
          style={styles.backIcon}
        >
          <FontAwesomeIcon icon={faArrowLeft} color={"#d4c600"} size={25} />
        </TouchableOpacity> */}
      {/* <Text style={styles.headerText}>Login</Text>
      </View> */}

      <View style={styles.wrapper}>
        {status === "register" ? (
          <View>
            <View style={styles.wrap}>
              <View style={styles.wrapTop}>
                <Text style={styles.wrapTopHeader}>Login</Text>
              </View>
              <View style={styles.wrapMiddle}>
                <View style={styles.wrapMiddleForm}>
                  <View style={styles.wrapMiddleFormInput}>
                    <Text style={styles.inputText}>
                      Email Address{" "}
                      {!emailDupe && email !== "" ? (
                        <Text style={{ color: "red" }}>
                          Email does not exist
                        </Text>
                      ) : (
                        ""
                      )}
                    </Text>
                    <TextInput
                      style={styles.input}
                      onChangeText={(e) => {
                        handleChange(e);
                      }}
                      //   value={email}
                      placeholder=""
                      // keyboardType="numeric"
                    />
                  </View>
                  <View style={styles.wrapMiddleFormInput}>
                    <Text style={styles.inputText}>Password:</Text>
                    <View style={styles.input2}>
                      <TextInput
                        style={styles.inputPass}
                        placeholderTextColor="#003f5c"
                        secureTextEntry={!seePassword}
                        autoCapitalize="none"
                        value={password}
                        onChangeText={(text) => setpassword(text)}
                      />
                      <TouchableOpacity
                        style={{ color: "green", right: 10 }}
                        onPress={() => setSeePassword(!seePassword)}
                      >
                        <FontAwesomeIcon
                          icon={seePassword ? faEye : faEyeSlash}
                          size={18}
                          color="#003f5c"
                        />
                      </TouchableOpacity>
                    </View>
                  </View>
                </View>
              </View>
              {/* {error ? <Text>{error}</Text> : null} */}

              <TouchableOpacity
                style={styles.btnReg}
                // disabled={emailDupe ? false : true}
                onPress={() => {
                  navigation.navigate("ForgotPassword");
                }}
              >
                <Text style={styles.btnTextReg}>Forgot Password?</Text>
                {/* <Text style={styles.btnTextReg}>Register here</Text> */}
              </TouchableOpacity>
              <View style={styles.wrapBottom}>
                <TouchableOpacity
                  style={styles.btn}
                  // disabled={emailDupe ? false : true}
                  onPress={() => {
                    handleLogin();
                  }}
                >
                  <Text style={styles.btnText}>Login</Text>
                </TouchableOpacity>
              </View>
              <TouchableOpacity
                style={styles.btnReg}
                // disabled={emailDupe ? false : true}
                onPress={() => {
                  navigation.navigate("Register");
                }}
              >
                <Text style={styles.btnTextReg}>No account yet?</Text>
                <Text style={styles.btnTextReg}>Register here</Text>
              </TouchableOpacity>
            </View>
          </View>
        ) : null}
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    backgroundColor: "#ffff",
    width: "100%",
    height: "100%",
  },
  wrapper: {
    height: "100%",
    width: "100%",
  },
  header: {
    alignItems: "center",
    width: "100%",
    top: 0,
    paddingLeft: 15,
    flexDirection: "row",
    borderColor: "#ddd",
    paddingBottom: 15,
    borderBottomWidth: 1,
  },
  headerText: {
    fontSize: 16,
    fontWeight: "600",
    marginLeft: 25,
  },
  wrap: {
    backgroundColor: "#fff",
    height: "100%",
    width: "100%",
    bottom: 0,
    borderColor: "#bebebe",
    borderRadius: 25,
  },

  wrapTop: {
    justifyContent: "center",
    alignItems: "center",
    height: 130,
    // backgroundColor:'#ffaa00',
    marginVertical: 15,
  },
  wrapTopHeader: {
    fontSize: 25,
    fontWeight: "600",
    color: "#ffaa00",
  },
  wrapMiddle: {
    justifyContent: "center",
    alignItems: "center",
    width: "100%",
  },
  wrapBottom: {
    justifyContent: "center",
    alignItems: "center",
  },
  wrapMiddleForm: {},
  wrapMiddleFormInput: {
    marginVertical: 10,
  },
  input: {
    height: 50,
    width: 300,
    margin: 12,
    borderWidth: 1,
    padding: 10,
    borderColor: "#bebebe",
    borderRadius: 10,
  },
  input2: {
    height: 50,
    width: 300,
    margin: 12,
    borderWidth: 1,
    padding: 10,
    borderColor: "#bebebe",
    borderRadius: 10,
    flexDirection: "row",
    justifyContent: "center",
    alignItems: "center",
  },
  inputPass: {
    height: 50,
    width: 250,
    // margin: 12,
    // borderWidth: 1,
    // padding: 10,
    // borderColor: "#bebebe",
    // borderRadius: 10,
  },
  inputText: {
    marginLeft: 15,
    fontSize: 16,
  },
  btn: {
    backgroundColor: "#ffaa00",
    paddingVertical: 15,
    paddingHorizontal: 55,
    marginTop: 30,
  },
  btnText: {
    color: "#fff",
    fontWeight: "600",
    letterSpacing: 1,
    fontSize: 16,
  },
  btnReg: {
    // backgroundColor: "#333",
    width: "100%",
    justifyContent: "center",
    alignContent: "center",
    paddingVertical: 15,
    paddingHorizontal: 55,
    marginTop: 30,
  },
  btnTextReg: {
    color: "#ffaa00",
    textAlign: "center",
    fontWeight: "600",
    letterSpacing: 1,
    fontSize: 16,
  },
});

export default Login;
