import AsyncStorage from "@react-native-async-storage/async-storage";
import { useNavigation } from "@react-navigation/native";
import React, { useEffect, useRef, useState } from "react";
import {
  TextInput,
  View,
  Text,
  StyleSheet,
  TouchableOpacity,
} from "react-native";
import {
  get_user_token,
  register_user,
  user_login,
} from "../../services/api/controllers/auth";
import { get_customer_login_id } from "../../services/api/controllers/customers";
import { update_order_item_by_reference_number } from "../../services/api/controllers/order";
import { create_transaction } from "../../services/obananapayApi/transaction_api";
import { update_payment } from "../../services/obananapayGatewayApi/controllers/payment_api";

const OTPAuth = ({
  setotpCheck,
  otp,
  setstatus,
  setsuccess,
  setloading,
  email,
  password,
  settoken,
  setuid,
}) => {
  const et1 = useRef();
  const et2 = useRef();
  const et3 = useRef();
  const et4 = useRef();
  const et5 = useRef();
  const et6 = useRef();
  const [f1, setF1] = useState("");
  const [f2, setF2] = useState("");
  const [f3, setF3] = useState("");
  const [f4, setF4] = useState("");
  const [f5, setF5] = useState("");
  const [f6, setF6] = useState("");
  const [errorOTP, seterrorOTP] = useState(false);
  const [count, setCount] = useState(20);
  const [error, seterror] = useState("");
  const [tokenHere, settokenHere] = useState("");

  // console.log("token:" + token);
  // console.log("uid:" + uid);
  const navigation = useNavigation();
  useEffect(() => {
    const interval = setInterval(() => {
      if (count == 0) {
        clearInterval(interval);
      } else {
        setCount(count - 1);
      }
    }, 1000);
    return () => {
      clearInterval(interval);
    };
  }, [count]);
  /* ---------------check if the  sent otp and the entered otp is the same--------------- */

  const otpValidate = () => {
    let enteredOtp = f1 + f2 + f3 + f4 + f5 + f6;
    if (enteredOtp == otp) {
      console.log(otp);
      setotpCheck(true);
      register_user({
        username: email.replace(/\s/g, "").toLowerCase(),
        password: password,
      })
        .then((result) => {
          if (result.status == 201) {
            //   setuserEmail(result.data.user.email);
            //   settoken(result.data.token);
            //   setuid(result.data.user._id);
            // send_email();
            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);
                  get_user_token({
                    token: result.data.token,
                  })
                    .then((results) => {
                      if (results.status == 200) {
                        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)
                              );
                              setuid(results.data.profile.userId);
                              setstatus("customerCreate");
                            }
                          })
                          .catch((error) => {
                            // setError(error.message);
                            console.log(error.message);
                          })
                          .finally(() => {
                            // setprodIsLoading(false); // Set loading to false when done loading
                          });

                        //   setauth(true);
                      } 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");
                } else {
                  seterror(result.message);
                  console.log("login error" + result);
                }
              })
              .catch((err) => {
                seterror(err);
                console.log(err);
                console.log(err + "failed to login");
              });
            //   setauth(true);
            console.log("login success");
          } else {
            seterror(result.message);
            console.log("login error" + result);
          }
        })
        .catch((err) => {
          seterror(err);
          console.log(err);
          console.log(err + "failed to login");
        });
    } else {
      setotpError(true);
    }
  };
  const phoneOTP = () => {
    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) => {
          setotp(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.wrap}>
        <Text style={styles.title1}>OTP Verification</Text>
        <Text style={styles.title}>
          Please enter the verification code we just sent on your email address .
        </Text>
        <View style={styles.otpView}>
          <TextInput
            ref={et1}
            style={[
              styles.inputView,
              { borderColor: f1.length >= 1 ? "green" : "#f57f17" },
            ]}
            keyboardType="number-pad"
            maxLength={1}
            value={f1}
            onChangeText={(txt) => {
              setF1(txt);
              if (txt.length >= 1) {
                et2.current.focus();
              }
            }}
          />
          <TextInput
            ref={et2}
            style={[
              styles.inputView,
              { borderColor: f2.length >= 1 ? "green" : "#f57f17" },
            ]}
            keyboardType="number-pad"
            maxLength={1}
            value={f2}
            onChangeText={(txt) => {
              setF2(txt);
              if (txt.length >= 1) {
                et3.current.focus();
              } else if (txt.length < 1) {
                et1.current.focus();
              }
            }}
          />

          <TextInput
            ref={et3}
            style={[
              styles.inputView,
              { borderColor: f3.length >= 1 ? "green" : "#f57f17" },
            ]}
            keyboardType="number-pad"
            maxLength={1}
            value={f3}
            onChangeText={(txt) => {
              setF3(txt);
              if (txt.length >= 1) {
                et4.current.focus();
              } else if (txt.length < 1) {
                et2.current.focus();
              }
            }}
          />

          <TextInput
            ref={et4}
            style={[
              styles.inputView,
              { borderColor: f4.length >= 1 ? "green" : "#f57f17" },
            ]}
            keyboardType="number-pad"
            maxLength={1}
            value={f4}
            onChangeText={(txt) => {
              setF4(txt);
              if (txt.length >= 1) {
                et5.current.focus();
              } else if (txt.length < 1) {
                et3.current.focus();
              }
            }}
          />

          <TextInput
            ref={et5}
            style={[
              styles.inputView,
              { borderColor: f5.length >= 1 ? "green" : "#f57f17" },
            ]}
            keyboardType="number-pad"
            maxLength={1}
            value={f5}
            onChangeText={(txt) => {
              setF5(txt);
              if (txt.length >= 1) {
                et6.current.focus();
              } else if (txt.length < 1) {
                et4.current.focus();
              }
            }}
          />

          <TextInput
            ref={et6}
            style={[
              styles.inputView,
              { borderColor: f6.length >= 1 ? "green" : "#f57f17" },
            ]}
            keyboardType="number-pad"
            maxLength={1}
            value={f6}
            onChangeText={(txt) => {
              setF6(txt);
              if (txt.length >= 1) {
                et6.current.focus();
              } else if (txt.length < 1) {
                et5.current.focus();
              }
            }}
          />
        </View>

        {errorOTP ? (
          <View style={{ width: "100%", marginBottom: 10 }}>
            <Text
              style={{
                fontSize: 20,
                fontWeight: "500",
                color: "#ed0000",
                alignSelf: "center",
                textAlign: "center",
                paddingTop: 10,
                paddingLeft: 10,
              }}
            >
              Wrong OTP!!
            </Text>
          </View>
        ) : null}
        <TouchableOpacity
          disabled={
            f1 !== "" &&
            f2 !== "" &&
            f3 !== "" &&
            f4 !== "" &&
            f5 !== "" &&
            f6 !== ""
              ? false
              : true
          }
          style={[
            styles.verifyOtpBtn,
            {
              backgroundColor:
                f1 !== "" &&
                f2 !== "" &&
                f3 !== "" &&
                f4 !== "" &&
                f5 !== "" &&
                f6 !== ""
                  ? "#4caf50"
                  : "orange",
            },
          ]}
          onPress={() => otpValidate()}
        >
          <Text style={styles.btntxt}>Next</Text>
        </TouchableOpacity>
        <View style={styles.resendView}>
          <Text
            style={{
              fontSize: 18,
              alignSelf: "flex-start",
              fontWeight: "700",
              color: count == 0 ? "orange" : "#7b7b7b",
            }}
            onPress={() => {
              phoneOTP();
            }}
          >
            Resend Code
          </Text>
          {count !== 0 && (
            <Text style={{ marginLeft: 20, fontSize: 18 }}>
              {count + " seconds"}
            </Text>
          )}
        </View>
      </View>
    </View>
  );
};
const styles = StyleSheet.create({
  container: {
    height: "100%",
    bottom: 0,
  },
  wrap: {
    backgroundColor: "#fff",
    height: "86%",
    bottom: 0,
    marginTop: 30,
    // borderWidth: 2,
    // borderColor: "#eeeeee",
    borderRadius: 25,
    padding: 10,
  },
  wrapTop: {
    height: "4%",
    bottom: 0,
  },
  wrapHeader: {
    justifyContent: "space-between",
    flexDirection: "row",
  },
  wrapHeaderText: {
    fontWeight: "600",
    letterSpacing: 1,
    fontSize: 16,
    color: "#2e2e2e",
  },
  title: {
    fontSize: 15,
    fontWeight: "500",
    marginTop: 5,
    marginLeft: 35,
    alignSelf: "flex-start",
    textAlign: "center",
    width: "83%",
    color: "#969696",
  },
  title1: {
    fontSize: 25,
    fontWeight: "700",
    marginTop: 10,
    marginLeft: 25,
    alignSelf: "center",
    textAlign: "center",
    width: "83%",
    color: "#525252",
  },
  otpView: {
    width: "100%",
    justifyContent: "center",
    alignItems: "center",
    flexDirection: "row",
    marginTop: 50,
  },
  inputView: {
    width: 50,
    height: 50,
    borderWidth: 0.5,
    borderRadius: 15,
    marginLeft: 10,
    textAlign: "center",
    fontSize: 18,
    fontWeight: "700",
  },
  verifyOtpBtn: {
    width: "40%",
    height: 45,
    backgroundColor: "orange",
    borderRadius: 15,
    alignSelf: "center",
    marginTop: 20,
    justifyContent: "center",
    alignItems: "center",
  },
  btntxt: {
    color: "#fff",
    fontSize: 20,
    fontWeight: "700",
  },
  resendView: {
    flexDirection: "row",
    alignSelf: "center",
    marginTop: 10,
    marginBottom: 30,
    fontWeight: "200",
  },
});
export default OTPAuth;
