import { faArrowLeft } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-native-fontawesome";
import AsyncStorage from "@react-native-async-storage/async-storage";
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 { send_email_api } from "../../services/obananapayApi/user_api";
import OTPAuth from "./OTP";

const Register = () => {
  const navigation = useNavigation();
  const [status, setstatus] = useState("register");
  const [email, setemail] = useState("");
  const [error, seterror] = useState("");
  const [otpSent, setotpSent] = useState("");
  const [otpCheck, setotpCheck] = useState("");
  const [success, setsuccess] = useState("");
  const [token, settoken] = useState("");
  const [fName, setfName] = useState("");
  const [lName, setlName] = useState("");
  const [phone, setphone] = useState("");
  const [uid, setuid] = useState("");

  const [loading, setloading] = useState("");
  const [emailDupe, setemailDupe] = useState("");

  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 handleRegister = (e) => {
    /* ---------------Login Function --------------- */
    send_email();
    setstatus("otp");
  };
  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 || undefined || [] || null) {
            setemail(e);
            setemailDupe(false);
          } else {
            setemailDupe(true);
          }
          // 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
      });
  };
  const handleCreateCustomer = (e) => {
    create_customer({
      first_name: fName,
      last_name: lName,
      user_email: email,
      phone_number: phone,
      role: "customer",
      login_id: uid,
    })
      .then((result) => {
        // console.log(result.data);

        if (result.status === 201) {
          console.log("success create customer" + result.data);
          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);
                console.log("login error" + result);
              }
            })
            .catch((err) => {
              seterror(err);
              console.log(err);
              console.log(err + "failed to login");
            });
          navigation.navigate("Home");
        }
      }) 
      .catch((error) => {
        // setError(error.message);
        console.log(error.message);
      })
      .finally(() => {
        // setprodIsLoading(false); // Set loading to false when done loading
      });
  };
  const send_email = () => {
    if (email) {
      const min = 100000; // Minimum 6-digit number
      const max = 999999; // Maximum 6-digit number
      const randomNumber = Math.floor(Math.random() * (max - min + 1)) + min;
      // const email2 = "kramblooda@gmail.com";
      send_email_api({
        email: email.replace(/\s/g, "").toLowerCase(),
        html: `<p>your OTP code to continue your obanana pay transaction is ${randomNumber} </p>`,
      })
        .then((result) => {
          setotpSent(randomNumber);
          if (result.status == 200) {
          } else {
            seterror(result.message);
          }

          console.log(result);
        })
        .catch((err) => {
          seterror(err);

          console.error(err);
          console.log(err + "failed to send email");
        });
    } else {
      //   setotpError(true);
    }
  };
  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}>Register</Text>
      </View> */}

      <View style={styles.wrapper}>
        {status === "register" ? (
          <View>
            <View style={styles.wrap}>
              <View style={styles.wrapTop}>
                <Text style={styles.wrapTopHeader}>Register</Text>
              </View>
              <View style={styles.wrapMiddle}>
                <View style={styles.wrapMiddleForm}>
                  <View style={styles.wrapMiddleFormInput}>
                    <Text style={styles.inputText}>
                      Email Address{" "}
                      {emailDupe ? (
                        <Text style={{ color: "red" }}>
                          Email already in used
                        </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>
                    <TextInput
                      style={styles.input}
                      onChangeText={(e) => {
                        setpassword(e);
                      }}
                      value={password}
                      placeholder=""
                      // keyboardType="numeric"
                      secureTextEntry={true}
                    />
                  </View>
                </View>
              </View>
              {error ? <Text>{error}</Text> : null}
              <View style={styles.wrapBottom}>
                <TouchableOpacity
                  style={styles.btn}
                  disabled={emailDupe ? true : false}
                  onPress={() => {
                    handleRegister();
                  }}
                >
                  <Text style={styles.btnText}>Register</Text>
                </TouchableOpacity>
              </View>
              <TouchableOpacity
                style={styles.btnReg}
                // disabled={emailDupe ? false : true}
                onPress={() => {
                  navigation.navigate("Login");
                }}
              >
                <Text style={styles.btnTextReg}>Already have an account?</Text>
                <Text style={styles.btnTextReg}>Login here</Text>
              </TouchableOpacity>
            </View>
          </View>
        ) : status === "otp" ? (
          <View>
            <OTPAuth
              otp={otpSent}
              setotpCheck={setotpCheck}
              setstatus={setstatus}
              settoken={settoken}
              email={email}
              password={password}
              setuid={setuid}
            />
          </View>
        ) : status === "customerCreate" ? (
          <View>
            <View style={styles.wrap}>
              <View style={styles.wrapTop}>
                <Text style={styles.wrapTopHeader}>Obanana </Text>
              </View>
              <View style={styles.wrapMiddle}>
                <View style={styles.wrapMiddleForm}>
                  <View style={styles.wrapMiddleFormInput}>
                    <Text style={styles.inputText}>First Name </Text>
                    <TextInput
                      style={styles.input}
                      onChangeText={(e) => {
                        setfName(e);
                      }}
                      value={fName}
                      placeholder=""
                      // keyboardType="numeric"
                    />
                  </View>
                  <View style={styles.wrapMiddleFormInput}>
                    <Text style={styles.inputText}>Last Name </Text>
                    <TextInput
                      style={styles.input}
                      onChangeText={(e) => {
                        setlName(e);
                      }}
                      value={lName}
                      placeholder=""
                      // keyboardType="numeric"
                    />
                  </View>
                  <View style={styles.wrapMiddleFormInput}>
                    <Text style={styles.inputText}>Phone Number </Text>
                    <TextInput
                      style={styles.input}
                      onChangeText={(e) => {
                        setphone(e);
                      }}
                      value={phone}
                      placeholder=""
                      // keyboardType="numeric"
                    />
                  </View>
                </View>
              </View>
              {error ? <Text>{error}</Text> : null}
              <View style={styles.wrapBottom}>
                <TouchableOpacity
                  style={styles.btn}
                  //   disabled={emailDupe ? true : false}
                  onPress={() => {
                    handleCreateCustomer();
                  }}
                >
                  <Text style={styles.btnText}>Register</Text>
                </TouchableOpacity>
              </View>
            
            </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,
  },
  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 Register;
