import { useNavigation } from "@react-navigation/native";
import axios from "axios";
import React, { useEffect, useRef, useState } from "react";
import {
  TextInput,
  View,
  Text,
  StyleSheet,
  TouchableOpacity,
} from "react-native";
import {
  update_order_item_by_reference_number,
  webhook,
} from "../../services/api/controllers/order";
import { create_transaction, get_user } from "../../services/obananapayApi/transaction_api";
import { update_payment } from "../../services/obananapayGatewayApi/controllers/payment_api";

const OTP = ({
  setotpCheck,
  otp,
  token,
  amount,
  desc,
  uid,
  setsuccess,
  setloading,
  pay_refno,
  username,
  email,
  number,
  setsuccessCOD,
  setlowBal,
}) => {
  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 [checkOTP, setcheckOTP] = useState(otp ?? "");
  const [resend, setresend] = useState(false);
  const [useResendOTP, setuseResendOTP] = useState(false);

  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]);
  useEffect(() => {
    if (resend) {
      setCount(20);
      const interval = setInterval(() => {
        if (count == 0) {
          clearInterval(interval);
        } else {
          setCount(count - 1);
        }
      }, 1000);
      setresend(false);
      return () => {
        clearInterval(interval);
      };
    }
  }, [resend]);
  /* ---------------check if the  sent otp and the entered otp is the same--------------- */

  const otpValidate = () => {
    // seterrorOTP(false);

    let enteredOtp = f1 + f2 + f3 + f4 + f5 + f6;
    console.log(checkOTP);
    console.log(enteredOtp + " " + checkOTP + " " + otp);
    console.log("isresend: " + resend);
    if (useResendOTP === true) {
      console.log("checking resend otp");

      if (enteredOtp.toString() == checkOTP.toString()) {
        console.log("success otp");
        setotpCheck(true);
        SendTransaction();
      } else {
        seterrorOTP(true);
      }
    } else {
      console.log("checking otp");

      if (enteredOtp.toString() == otp.toString()) {
        console.log("success otp");
        setotpCheck(true);
        SendTransaction();
      } else {
        seterrorOTP(true);
      }
    }
  };
  const SendTransaction = () => {
    // Get the URL search params

    // Get the 'amount' and 'description' values

    const characters =
      "0123456789abcdefghijklmnopqrstubwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    let refno = "";
    for (let i = 0; i < 13; i++) {
      const randomIndex = Math.floor(Math.random() * characters.length);
      refno += characters.charAt(randomIndex);
    }
    const receiverId = "6458dd6066139b3fee29a9cf";
    setloading(true);
    /* ---------------Get User--------------- */
    get_user({
      id: uid,
      token: token,
    })
      .then((res) => {
        console.log(res.data);
        if (parseFloat(amount) < parseFloat(res.data.balance)) {
          create_transaction({
            body: {
              from_id: uid,
              to_id: receiverId,
              amount: parseFloat(amount),
              type: "transfer",
              notes: desc,
              ref_no: refno,
            },
            token: token,
          })
            .then((result) => {
              setloading(false);
              if (result.status === 200) {
                update_payment({
                  id: pay_refno,
                  body: {
                    status: "paid",
                    payments: {
                      attributes: {
                        amount: amount * 100,
                        billing: {
                          email: email,
                          name: username,
                          phone: number,
                        },
                        currency: "PHP",
                        description: desc,
                        disputed: false,
                        fee: 0,
                        livemode: false,
                        net_amount: amount * 100,
                        origin: "links",
                        payment_intent_id: null,
                        payout: null,
                        source: {
                          type: "obananapay",
                        },
                        statement_descriptor: "Obanana E-commerce Checkout",
                        status: "paid",
                        tax_amount: 0,
                        taxes: [],
                        available_at: null,
                        paid_at: null,
                      },
                    },
                  },
                  // token: token,
                })
                  .then((results) => {
                    if (results.status === 200) {
                      console.log("successful update payment");
                      // update_order_item_by_reference_number({
                      //   refId: pay_refno,
                      //   body: {
                      //     payment_status: "PAID",
                      //     order_status: "TO SHIP",

                      //     details: results.data,
                      //   },
                      //   // token: token,
                      // })
                      //   .then(() => {
                      //     if (result.status === 200) {
                      //       console.log("successful update payment on obanana order");

                      //       setsuccess(true);
                      //       // navigation.reset({
                      //       //   index: 0,
                      //       //   routes: [{ name: 'Home' }],
                      //       // });
                      //     } else {
                      //       console.log("failed update payment on obanana order");
                      //     }
                      //   })
                      //   .catch((err) => {
                      //     console.error(err);
                      //   });
                      const characters =
                        "0123456789abcdefghijklmnopqrstubwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
                      let refno1 = "";
                      for (let i = 0; i < 16; i++) {
                        const randomIndex = Math.floor(
                          Math.random() * characters.length
                        );
                        refno1 += characters.charAt(randomIndex);
                      }
                      const refnoFinal = "obn_evt_id_" + refno1;
                      const currentDate = new Date();
                      const universalDate = currentDate.toISOString();
                      webhook({
                        body: {
                          data: {
                            id: refnoFinal,
                            type: "event",
                            attributes: {
                              type: "link.payment.paid",
                              livemode: false,
                              data: results.data,
                              previous_data: {},
                              created_at: universalDate,
                              updated_at: universalDate,
                            },
                          },
                        },
                      })
                        .then((res) => {
                          if (res.status === 200) {
                            console.log(
                              "successful update payment on obanana order"
                            );
                            setsuccessCOD(true);
                            setsuccess(true);
                            // navigation.reset({
                            //   index: 0,
                            //   routes: [{ name: 'Home' }],
                            // });
                          } else {
                            console.log(
                              "failed update payment on obanana order"
                            );
                          }
                        })
                        .catch((err) => {
                          console.error(err);
                        });
                    } else {
                      console.log("failed update payment");
                    }
                  })
                  .catch((err) => {
                    console.error(err);
                  });
                // create_notification({
                //   body: {
                //     from_id: receiverId,
                //     to_id: receiverId,
                //     message: `you received ₱${amount} from Obanana E-commerce`,
                //     title: "Received Money fom Obanana",
                //   },
                //   token: token,
                // })
                //   .then((result) => {})
                //   .catch((err) => {
                //     console.error(err);
                //   });
              } else {
                console.log("failed obanana payment transaction");
              }
              console.log(" transaction status: " + result.status);
            })
            .catch((err) => {
              console.error(err);
            });
        } else {
          setloading(false);
          setlowBal(true);
        }
      })
      .catch((err) => {
        console.error(err);
        console.log(err + "failed to get uset");
      });
    // create_transaction({
    //   body: {
    //     from_id: uid,
    //     to_id: receiverId,
    //     amount: parseFloat(amount),
    //     type: "transfer",
    //     notes: desc,
    //     ref_no: refno,
    //   },
    //   token: token,
    // })
    //   .then((result) => {
    //     setloading(false);
    //     if (result.status === 200) {
    //       update_payment({
    //         id: pay_refno,
    //         body: {
    //           status: "paid",
    //           payments: {
    //             attributes: {
    //               amount: amount * 100,
    //               billing: {
    //                 email: email,
    //                 name: username,
    //                 phone: number,
    //               },
    //               currency: "PHP",
    //               description: desc,
    //               disputed: false,
    //               fee: 0,
    //               livemode: false,
    //               net_amount: amount * 100,
    //               origin: "links",
    //               payment_intent_id: null,
    //               payout: null,
    //               source: {
    //                 type: "obananapay",
    //               },
    //               statement_descriptor: "Obanana E-commerce Checkout",
    //               status: "paid",
    //               tax_amount: 0,
    //               taxes: [],
    //               available_at: null,
    //               paid_at: null,
    //             },
    //           },
    //         },
    //         // token: token,
    //       })
    //         .then((results) => {
    //           if (results.status === 200) {
    //             console.log("successful update payment");
    //             // update_order_item_by_reference_number({
    //             //   refId: pay_refno,
    //             //   body: {
    //             //     payment_status: "PAID",
    //             //     order_status: "TO SHIP",

    //             //     details: results.data,
    //             //   },
    //             //   // token: token,
    //             // })
    //             //   .then(() => {
    //             //     if (result.status === 200) {
    //             //       console.log("successful update payment on obanana order");

    //             //       setsuccess(true);
    //             //       // navigation.reset({
    //             //       //   index: 0,
    //             //       //   routes: [{ name: 'Home' }],
    //             //       // });
    //             //     } else {
    //             //       console.log("failed update payment on obanana order");
    //             //     }
    //             //   })
    //             //   .catch((err) => {
    //             //     console.error(err);
    //             //   });
    //             const characters =
    //               "0123456789abcdefghijklmnopqrstubwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    //             let refno1 = "";
    //             for (let i = 0; i < 16; i++) {
    //               const randomIndex = Math.floor(
    //                 Math.random() * characters.length
    //               );
    //               refno1 += characters.charAt(randomIndex);
    //             }
    //             const refnoFinal = "obn_evt_id_" + refno1;
    //             const currentDate = new Date();
    //             const universalDate = currentDate.toISOString();
    //             webhook({
    //               body: {
    //                 data: {
    //                   id: refnoFinal,
    //                   type: "event",
    //                   attributes: {
    //                     type: "link.payment.paid",
    //                     livemode: false,
    //                     data: results.data,
    //                     previous_data: {},
    //                     created_at: universalDate,
    //                     updated_at: universalDate,
    //                   },
    //                 },
    //               },
    //             })
    //               .then((res) => {
    //                 if (res.status === 200) {
    //                   console.log("successful update payment on obanana order");
    //                   setsuccessCOD(true);
    //                   setsuccess(true);
    //                   // navigation.reset({
    //                   //   index: 0,
    //                   //   routes: [{ name: 'Home' }],
    //                   // });
    //                 } else {
    //                   console.log("failed update payment on obanana order");
    //                 }
    //               })
    //               .catch((err) => {
    //                 console.error(err);
    //               });
    //           } else {
    //             console.log("failed update payment");
    //           }
    //         })
    //         .catch((err) => {
    //           console.error(err);
    //         });
    //       // create_notification({
    //       //   body: {
    //       //     from_id: receiverId,
    //       //     to_id: receiverId,
    //       //     message: `you received ₱${amount} from Obanana E-commerce`,
    //       //     title: "Received Money fom Obanana",
    //       //   },
    //       //   token: token,
    //       // })
    //       //   .then((result) => {})
    //       //   .catch((err) => {
    //       //     console.error(err);
    //       //   });
    //     } else {
    //       console.log("failed obanana payment transaction");
    //     }
    //     console.log(" transaction status: " + result.status);
    //   })
    //   .catch((err) => {
    //     console.error(err);
    //   });
  };

  const send_email = () => {
    setuseResendOTP(false);
    const apiKey =
      "ODA4MDc4ZThjMDA4NjVhYzU4MTcyNDJjNTMxY2JlZGU6MGQ4ODg3ZTdiZjY1ZWNkMmQ0NzdiOWJhZGIyYTJhY2Q="; // Replace with your Mailjet API key
    const apiUrl = "https://api.mailjet.com/v3.1/send";

    // const otp = generateOTP(6); // You should have a function to generate the OTP
    // const email2 = "kramblooda@gmail.com";
    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 requestData = {
      Messages: [
        {
          From: {
            Email: "webdev@obanana.com",
            Name: "Obanana B2B",
          },
          To: [
            {
              Email: email,
              Name: "Subscriber",
            },
          ],
          Subject: "Obanana OTP",
          TextPart: "Greetings from Obanana!",
          HTMLPart: `This is your OTP - <b>${randomNumber}</b>. Do not share this with anyone.`,
        },
      ],
    };

    const config = {
      headers: {
        "Content-Type": "application/json",
        Authorization: `Basic ${apiKey}`,
      },
    };

    axios
      .post(apiUrl, requestData, config)
      .then((response) => {
        const status = response.data.Messages[0].Status;
        console.log(response.data.Messages[0].Status);
        console.log(randomNumber);
        setcheckOTP(randomNumber);
        setresend(true);
        setuseResendOTP(true);

        console.log("resending " + resend);
        return `${status},${randomNumber}`;
      })
      .catch((error) => {
        console.error("Error sending OTP email:", error);
        // Handle the error here
      });

    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;

      // You would need to implement the generateOTP function as well.

      // send_email_api({
      //   email: email2.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);
    }
  };

  // attributes: {
  //   amount: amount,
  //   billing: {
  //     email: email,
  //     name: name,
  //     phone: contact,
  //   },
  //   currency: "PHP",
  //   description: `${product.product_name}, ordered from obanana e-commerce`,,
  //   disputed: false,
  //   fee: 0,
  //   livemode: false,
  //   net_amount: amount,
  //   origin: "links",
  //   payment_intent_id: null,
  //   payout: null,
  //   source: {
  //     type: "obananapay",
  //   },
  //   statement_descriptor: "Obanana E-commerce Checkout",
  //   status: "paid",
  //   tax_amount: 4,
  //   taxes: [

  //   ],
  //   available_at: null,
  //   paid_at: null,
  // },
  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 Phone Number .
        </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",
            }}
            // disabled={f1 && f2 && f3 && f4 && f5 && f6 ? false : true}
            onPress={() => {
              send_email();
            }}
          >
            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 OTP;
