import { faAngleRight, 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, useRoute } from "@react-navigation/native";
import React, { useEffect, useState } from "react";
import {
  View,
  Text,
  StyleSheet,
  TouchableOpacity,
  TextInput,
  Image,
  Dimensions,
  Platform,
  ActivityIndicator,
  // Modal,
} from "react-native";
// import { user } from "../../constants/user";
import { update_order } from "../../services/api/controllers/order";
import Auth from "../../services/obananapay/Auth";
import { create_payment } from "../../services/obananapayGatewayApi/controllers/payment_api";
import Modal from "react-native-modal";
import { useToast } from "react-native-toast-notifications";
const deviceWidth = Dimensions.get("window").width;

const CheckOut = () => {
  //NOTE !!!! must pass the update product details to the shipping option and payment method page!!!! to prevent  error

  const [message, setmessage] = useState("");
  const [paymessage, setpaymessage] = useState("");
  const [pay_refno, setpay_refno] = useState("");
  const [codLoad, setcodLoad] = useState(false);

  const [billingAdd, setbillingAdd] = useState("");
  const [successCOD, setsuccessCOD] = useState(false);
  const [orderIdC, setorderIdC] = useState("");
  const [token, settoken] = useState("");

  const [amount, setamount] = useState(0);
  const toast = useToast();

  const [modalVisible, setModalVisible] = useState(false);
  const [shippingMethod, setshippingMethod] = useState(
    "select shipping method"
  );
  const [paymentMethod, setpaymentMethod] = useState("select shipping method");
  const [recipientDetails, setrecipientDetails] = useState([]);
  const [user, setuser] = useState([]);
  console.log(successCOD);
  useEffect(() => {
    /* ---------------Check for the user saved email--------------- */
    // setsuccessCOD(false)
    AsyncStorage.getItem("AccessToken")
      .then((pass) => {
        if (pass) {
          settoken(pass);
        }
      })
      .catch((error) => {
        console.log(error + "weeewwww");
      });
    AsyncStorage.getItem("userData")
      .then((pass) => {
        const userDataArray = JSON.parse(pass);
        setuser(userDataArray);
        const ship = userDataArray[0]?.address.find(
          (address) => address?.shipping === true
        );
        if (ship) {
          setrecipientDetails(ship);
        }

        const bill = userDataArray[0]?.address?.find(
          (address) => address.billing === true
        );
        setbillingAdd(bill);
        console.log(pass);
      })
      .catch((error) => {
        console.log(error + "weeewwww");
      });
  }, []);
  // console.log(shippingAddress)
  const navigation = useNavigation();
  const route = useRoute();
  const { product, shipMethod, payMethod, address, orderId } = route.params;
  console.log(orderId);
  useEffect(() => {
    setshippingMethod(shipMethod ?? "select shipping method");
  }, [shipMethod]);
  useEffect(() => {
    setpaymentMethod(payMethod ?? "select payment method");
  }, [payMethod]);
  useEffect(() => {
    setrecipientDetails(address ?? null);
  }, [address]);
  console.log(product);
  useEffect(() => {
    const shippingAddress = user[0]?.address?.find(
      (address) => address.shipping === true
    );
    if (shippingAddress) {
      setrecipientDetails(shippingAddress);
    }
    const billingAddress = user[0]?.address?.find(
      (address) => address.billing === true
    );
    setbillingAdd(billingAddress);
  }, []);
  console.log(billingAdd);
  const checkOutClicked = () => {
    setsuccessCOD(false);
    console.log(
      "he--------------------------------------------------------" +
        paymentMethod
    );
    if (recipientDetails) {
      if (paymentMethod === "Obananapay") {
        const amount = parseFloat(product.total_amount) * 100;
        create_payment({
          body: {
            amount: amount,
            description: `${product.items[0].product.name} (${product.items[0].quantity} qty), ordered from obanana e-commerce`,
          },
        })
          .then((result) => {
            console.log(
              "successful transaction" + result.data.attributes.reference_number
            );
            const currentDate = new Date();
            const iso8601String = currentDate.toISOString();
            if (result.status === 200) {
              setpay_refno(result.data.attributes.reference_number);
              const shipFee = product.shipping_fee ?? 50;

              update_order({
                token: token,
                id: orderId,
                body: {
                  payment_method: paymentMethod,
                  billing_address: {
                    billing_first_name: billingAdd?.first_name,
                    billing_last_name: billingAdd?.last_name,
                    billing_company: billingAdd?.company,
                    billing_email: billingAdd?.email,
                    billing_phone: billingAdd?.phone,
                    billing_address_1: billingAdd?.address_1,
                    billing_address_2: billingAdd?.address_2,
                    billing_city: billingAdd?.city,
                    billing_barangay: billingAdd?.barangay,
                    billing_state: billingAdd?.province,
                    billing_country: billingAdd?.country,
                  },
                  shipping_address: {
                    shipping_first_name: recipientDetails?.first_name,
                    shipping_last_name: recipientDetails?.last_name,
                    shipping_company: recipientDetails?.company,
                    shipping_email: recipientDetails?.email,
                    shipping_phone: recipientDetails?.phone,
                    shipping_address_1: recipientDetails?.address_1,
                    shipping_address_2: recipientDetails?.address_2,
                    shipping_city: recipientDetails?.city,
                    shipping_barangay: recipientDetails?.barangay,
                    shipping_state: recipientDetails?.province,
                    shipping_country: recipientDetails?.country,
                  },
                  order_date: iso8601String,
                  payment: {
                    status: "UNPAID",
                    reference_number: result.data.attributes.reference_number,
                  },
                  total_amount:
                    result.data.attributes.amount / 100 + parseFloat(shipFee),
                },
              })
                .then((results) => {
                  if (results.status === 200) {
                    const shipFee = product.shipping_fee
                      ? product.shipping_fee * 100
                      : 500;
                    setamount(
                      parseFloat(result.data.attributes.amount) +
                        parseFloat(shipFee)
                    );
                    setpaymessage(result.data.attributes.description);
                    setModalVisible(!modalVisible);
                    console.log(
                      "order update id: " +
                        results.data +
                        "orderId: " +
                        orderId +
                        "amount: " +
                        result.data.attributes.amount
                    );
                  } else {
                    console.log("update order failed");
                  }
                })
                .catch((err) => {
                  console.error(err);
                });
            } else {
              console.log("create payment link failed");
            }
          })
          .catch((err) => {
            console.error(err);
          });
      } else if (paymentMethod === "Cash On Delivery") {
        setModalVisible(!modalVisible);
      } else {
        toast.show("Please select payment method!", {
          type: "danger",
          placement: "top",
          duration: 3000,
          offset: 30,
          animationType: "slide-in",
        });
      }
    } else {
      toast.show("Please select delivery address first!", {
        type: "danger",
        placement: "top",
        duration: 3000,
        offset: 30,
        animationType: "slide-in",
      });
    }
  };
  const CODpay = () => {
    setcodLoad(true);

    const characters =
      "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    let refno = "";

    for (let i = 0; i < 8; i++) {
      const randomIndex = Math.floor(Math.random() * characters.length);
      refno += characters.charAt(randomIndex);
    }

    const currentDate = new Date();
    const iso8601String = currentDate.toISOString();
    const shipFee = product.shipping_fee ?? 50;
    update_order({
      token: token,
      id: orderId,
      body: {
        payment_method: paymentMethod,
        billing_address: {
          billing_first_name: billingAdd?.first_name,
          billing_last_name: billingAdd?.last_name,
          billing_company: billingAdd?.company,
          billing_email: billingAdd?.email,
          billing_phone: billingAdd?.phone,
          billing_address_1: billingAdd?.address_1,
          billing_address_2: billingAdd?.address_2,
          billing_city: billingAdd?.city,
          billing_barangay: billingAdd?.barangay,
          billing_state: billingAdd?.province,
          billing_country: billingAdd?.country,
        },
        shipping_address: {
          shipping_first_name: recipientDetails?.first_name,
          shipping_last_name: recipientDetails?.last_name,
          shipping_company: recipientDetails?.company,
          shipping_email: recipientDetails?.email,
          shipping_phone: recipientDetails?.phone,
          shipping_address_1: recipientDetails?.address_1,
          shipping_address_2: recipientDetails?.address_2,
          shipping_city: recipientDetails?.city,
          shipping_barangay: recipientDetails?.barangay,
          shipping_state: recipientDetails?.province,
          shipping_country: recipientDetails?.country,
        },
        order_date: iso8601String,
        payment: {
          status: "UNPAID",
          reference_number: refno,
        },
        total_amount: parseFloat(product.total_amount) + parseFloat(shipFee),
        status: "TO PAY",
        // shipping_fee: product.shipping_fee ?? 50,
      },
    })
      .then((results) => {
        if (results.status === 200) {
          // setamount(result.data.attributes.amount);
          // setpaymessage(result.data.attributes.description);
          // setModalVisible(!modalVisible);
          setsuccessCOD(true);
          // console.log(
          //   "order update id: " +
          //     results.data +
          //     "orderId: " +
          //     orderId +
          //     "amount: " +
          //     result.data.attributes.amount
          // );
        } else {
          setsuccessCOD("error");
          console.log("update order failed");
        }
      })
      .catch((err) => {
        console.error(err);
      });
  };
  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}>Checkout</Text>
      </View>
      <View style={styles.wrapper}>
        <View style={styles.content}>
          <TouchableOpacity
            style={styles.subContent}
            onPress={() =>
              navigation.navigate("AddressSelection", {
                product,
                shipMethod: shippingMethod,
                payMethod: paymentMethod,
                address: recipientDetails,
                orderId: orderId,
                address: user[0]?.address,
              })
            }
          >
            <Text style={styles.subContentText}>DELIVERY ADDRESS</Text>
            <View style={styles.add}>
              <Text style={styles.addText} numberOfLines={4}>
                {recipientDetails !== null
                  ? `${recipientDetails?.first_name} ${
                      recipientDetails?.last_name
                    }, ${recipientDetails?.phone} ${
                      recipientDetails?.address_1 +
                      " " +
                      recipientDetails?.address_2 +
                      ", " +
                      recipientDetails?.city +
                      " " +
                      recipientDetails?.province +
                      " "
                    }${
                      recipientDetails?.country === "PH"
                        ? "Philippines"
                        : recipientDetails?.country
                    }`
                  : "select address"}
              </Text>
            </View>
            <FontAwesomeIcon icon={faAngleRight} color={"#ffaa00"} size={16} />
          </TouchableOpacity>

          <View style={styles.subContent1}>
            <Text style={styles.subContentText}>
              <Text style={styles.subContentTexthead}>
                {product.items[0].vendor_name}
              </Text>
            </Text>
            <View style={styles.card}>
              <View style={styles.imgWrap}>
                <Image
                  style={{ width: 50, height: 50, resizeMode: "cover" }}
                  source={{
                    uri: `${
                      product.items[0].product.product_image !== ""
                        ? product.items[0].product.product_image
                        : "https://wkdonlinedogtraining.com/wp-content/themes/wkd-wp/build/images/bg-no-img-big.jpg"
                    }`,
                  }}
                />
              </View>
              <View style={styles.wrapper}>
                <View style={styles.details}>
                  <Text style={styles.text} numberOfLines={2}>
                    {product.items[0].product.name}
                  </Text>

                  <View style={styles.rateCon}>
                    {product.items[0].price ? (
                      <>
                        <View style={styles.priceCon}>
                          <Text
                            style={
                              product?.sale_price
                                ? styles.textPricePromo
                                : styles.textPrice
                            }
                          >
                            ₱
                            {parseFloat(product.items[0].price).toLocaleString(
                              "en-US"
                            )}
                          </Text>
                        </View>
                      </>
                    ) : (
                      <Text>No price </Text>
                    )}
                    <Text style={styles.qty}>
                      {" "}
                      {product.items[0].quantity} qty{" "}
                    </Text>
                  </View>
                </View>
              </View>
            </View>
          </View>
          {/* 
          <TouchableOpacity
            style={styles.subContent}
            onPress={() =>
              navigation.navigate("ShippingOption", {
                product,
                shipMethod: shippingMethod,
                payMethod: paymentMethod,
                address: recipientDetails,
                orderId: orderId,
              })
            }
          >
            <Text style={styles.subContentText}>SHIPPING OPTION</Text>
            <View style={styles.wallet}>
              <Text style={styles.addText}>{shippingMethod}</Text>
            </View>
            <FontAwesomeIcon icon={faAngleRight} color={"#ffaa00"} size={16} />
          </TouchableOpacity>
          <View style={styles.subContent}>
            <Text style={styles.subContentText}>MESSAGE</Text>
            <TextInput
              style={styles.input}
              onChangeText={() => setmessage()}
              value={message}
              numberOfLines={2}
              placeholder="write a message"
            />
          </View> */}
          <TouchableOpacity style={styles.subContent}>
            <Text style={styles.subContentText}>ORDER TOTAL</Text>
            <Text style={styles.addText}>
              ₱
              {parseFloat(product.items[0].price) *
                parseInt(product.items[0].quantity)}
            </Text>
          </TouchableOpacity>
          <TouchableOpacity
            style={styles.subContent}
            onPress={() =>
              navigation.navigate("Paymentoption", {
                product,
                shipMethod: shippingMethod,
                payMethod: paymentMethod,
                address: recipientDetails,
                orderId: orderId ? orderId : null,
              })
            }
          >
            <Text style={styles.subContentText}>PAYMENT OPTION</Text>
            <View style={styles.wallet}>
              <Text style={styles.addText}>{paymentMethod}</Text>
            </View>
            <FontAwesomeIcon icon={faAngleRight} color={"#ffaa00"} size={16} />
          </TouchableOpacity>
          <View style={styles.subContent1}>
            <Text style={styles.subContentText}>PAYMENT DETAILS</Text>
            <View style={styles.payCon}>
              <View style={styles.subContent2}>
                <Text style={styles.subContentText2}>
                  Merchandise Sub Total:
                </Text>
                <Text style={styles.subContentTexthead}>
                  ₱{product.items[0].price}
                </Text>
              </View>

              <View style={styles.subContent2}>
                <Text style={styles.subContentText2}>Shipping:</Text>
                <Text style={styles.subContentTexthead}>
                  ₱{product.shipping_fee ?? 50.0}
                </Text>
              </View>

              <View style={styles.subContent2}>
                <Text style={styles.subContentText2}>Total: </Text>
                <Text style={styles.subContentTexthead}>
                  ₱
                  {parseFloat(product.total_amount, 10) +
                    parseFloat(product.shipping_fee ?? 50.0)}
                </Text>
              </View>
            </View>
          </View>
        </View>
      </View>
      <View style={styles.footer}>
        {successCOD === true ? (
          <>
            <Text style={styles.footerBtnText2}>Completed Transaction</Text>
          </>
        ) : (
          <TouchableOpacity
            style={styles.footerBtn}
            onPress={() => checkOutClicked()}
          >
            <Text style={styles.footerBtnText}>Order Now</Text>
          </TouchableOpacity>
        )}
      </View>
      <Modal
        animationType="slide"
        animationIn={"slideInUp"}
        transparent={true}
        isVisible={modalVisible}
        onSwipeComplete={() => setModalVisible(false)}
        swipeDirection={["down"]}
        swipeThreshold="100"
        backdropOpacity={0.2}
        style={{ margin: 0 }}
        propagateSwipe={true}
        deviceWidth={deviceWidth}
        onRequestClose={() => {
          setModalVisible(!modalVisible);
        }}
      >
        {paymentMethod === "Cash On Delivery" ? (
          <View style={styles.CodWrap}>
            {successCOD === true ? (
              <>
                <Text>Successful Order!</Text>
                <View style={styles.footer}>
                  <TouchableOpacity
                    style={styles.footerBtn}
                    onPress={() => navigation.navigate("Home")}
                  >
                    <Text style={styles.footerBtnText}>Exit</Text>
                  </TouchableOpacity>
                </View>
              </>
            ) : successCOD === "error" ? (
              <>
                <Text>Failed Order! Please try again later</Text>
                <View style={styles.footer}>
                  <TouchableOpacity
                    style={styles.footerBtn}
                    onPress={() => navigation.navigate("Home")}
                  >
                    <Text style={styles.footerBtnText}>Exit</Text>
                  </TouchableOpacity>
                </View>
              </>
            ) : (
              <>
                <Text>
                  Checkout order using Cash On Delivery payment method?
                </Text>
                <View style={styles.footer}>
                  <TouchableOpacity
                    style={styles.footerBtn}
                    onPress={() => CODpay()}
                    disabled={codLoad}
                  >
                    <Text style={styles.footerBtnText}>
                      {" "}
                      {codLoad ? (
                        <ActivityIndicator size="large" color="#ffffff" />
                      ) : (
                        "Continue"
                      )}
                    </Text>
                  </TouchableOpacity>
                </View>
              </>
            )}
          </View>
        ) : (
          <Auth
            onRequestClose={setModalVisible}
            amount={amount}
            pay_refno={pay_refno}
            desc={paymessage}
            setsuccessCOD={setsuccessCOD}
            username={user[0]?.first_name}
            email={user[0]?.user_email}
            number={"+63" + user[0]?.phone_number}
          />
        )}
      </Modal>
    </View>
  );
};
const styles = StyleSheet.create({
  container: {
    backgroundColor: "#fff",
    height: "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,
  },
  add: {
    width: "50%",
  },
  input: {
    width: "60%",
  },
  wallet: {
    // width: '50%'
  },
  footer: {
    position: "absolute",
    bottom: 0,
    width: "100%",
    justifyContent: "center",
    alignItems: "center",
    paddingVertical: 10,
  },
  footerBtn: {
    backgroundColor: "#ff5e00",
    width: "90%",
    paddingVertical: 10,
    borderRadius: 20,
    // borderColor:'#ffff',
    justifyContent: "center",
    alignItems: "center",
  },
  footerBtnText: {
    color: "#fff",
    fontSize: 16,
  },
  footerBtnText2: {
    color: "#353535",
    fontSize: 16,
  },
  wrapper: {
    // height: "85%",

    width: "100%",
    height: "100%",
  },
  content: {
    width: "100%",
    justifyContent: "center",
    alignItems: "center",
  },
  subContent: {
    width: "98%",
    justifyContent: "space-between",
    flexDirection: "row",
    alignItems: "center",
    padding: 10,
    // height: 60,
    borderColor: "#f0f0f0dd",
    borderWidth: 1,
  },
  subContent1: {
    width: "98%",
    justifyContent: "center",
    // flexDirection: "row",
    // alignItems: "center",
    padding: 15,
    // height: 60,
    borderColor: "#f0f0f0dd",
    borderWidth: 1,
  },
  subContent2: {
    width: "98%",
    justifyContent: "space-between",
    flexDirection: "row",
    // alignItems: "center",
    padding: 10,
    // height: 60,
    borderColor: "#f0f0f0dd",
    // borderWidth: 1,
  },
  subContentText: {
    fontWeight: "600",
    color: "#494949",
  },
  subContentText2: {
    width: "90%",
    flexDirection: "row",
    justifyContent: "space-between",
    // backgroundColor: "#b8141433",
  },
  subContentTexthead: {
    fontWeight: "600",
    color: "#000000",
  },
  addText: {
    color: "#5f5f5f",
    textAlign: "left",
  },
  imgWrap: {
    padding: 10,
  },
  card: {
    height: 80,
    flexDirection: "row",
    // justifyContent: "center",
    alignItems: "center",
    borderColor: "#f0f0f0dd",
    borderWidth: 1,
    padding: 10,
    marginTop: 10,
  },
  payCon: {
    width: "80%",
  },
  priceCon: {
    flexDirection: "row",
    paddingVertical: 10,
  },
  rateCon: {
    width: "75%",
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
  },
  qty: {
    fontSize: 14,
    color: "#5f5f5f",
  },
  textPrice: {
    fontSize: 14,
    fontWeight: "600",
    textTransform: "capitalize",
    color: "#ffaa00",
  },
  textPricePromo: {
    fontSize: 14,
    fontWeight: "600",
    textTransform: "capitalize",
    textDecorationLine: "line-through",
    color: "#ffaa00",
  },
  details: {
    // width: "50%",
  },
  text: {
    fontSize: 14,
    fontWeight: "500",
    width: "75%",
  },
  CodWrap: {
    backgroundColor: "#fff",
    marginTop: 20,
    height: "50%",
    bottom: 0,
    borderWidth: 2,
    borderColor: "#eeeeee",
    // borderTopRightRadius: 25,
    borderRadius: 25,
    borderTopLeftRadius: 25,
    padding: 10,
    justifyContent: "center",
    alignItems: "center",
  },
});

export default CheckOut;
