import React, { useEffect, useState } from "react";
import {
  View,
  Text,
  StyleSheet,
  Image,
  TouchableOpacity,
  Dimensions,
} from "react-native";

import ReceiptCard from "./Receipt";
import Modal from "react-native-modal";
import { update_order } from "../../../services/api/controllers/order";
import AsyncStorage from "@react-native-async-storage/async-storage";
const deviceWidth = Dimensions.get("window").width;
const ToReceiveCard = ({ cart }) => {
  const [modalVisible, setModalVisible] = useState(false);
  const [modalVisible1, setModalVisible1] = useState(false);
  const [token, settoken] = useState("");

  const [estimatedDate, setestimatedDate] = useState("");
  const [completed, setcompleted] = useState(false);

  // Assuming cart.deliveryDate is a string like "2023-09-25T15:30:00Z"
  const expectedDeliveryDateMin = new Date(cart.expectedDeliveryDateMin);
  const month = expectedDeliveryDateMin.toLocaleString("en-US", {
    month: "short",
  });
  const day = expectedDeliveryDateMin.getDate();
  const options = {
    year: "numeric",
    month: "short",
    day: "2-digit",
  };
  const options2 = {
    month: "short",
    day: "2-digit",
  };
  const time = expectedDeliveryDateMin.toLocaleString("en-US", {
    timeZone: "Asia/Manila",
    ...options2,
  });
  const expectedDeliveryDateMax = new Date(cart.expectedDeliveryDateMax);

  const time2 = expectedDeliveryDateMax.toLocaleString("en-US", {
    timeZone: "Asia/Manila",
    ...options,
  });

  const total = parseFloat(cart?.total_amount);

  // Format the day with leading zeros if needed (e.g., "01" instead of "1")
  const formattedDay = day < 10 ? `0${day}` : day;

  // Create the final formatted date string "Sept. 25"
  const philippinesTime = `${month}. ${formattedDay} `;
  useEffect(() => {
    AsyncStorage.getItem("AccessToken")
      .then((pass) => {
        if (pass) {
          settoken(pass);
        }
      })
      .catch((error) => {
        console.log(error + "weeewwww");
      });
    // Assuming cart?.updatedAt holds a string in MongoDB updatedAt format
    let updatedAtString = cart?.updatedAt; // Replace cart?.updatedAt with your actual value

    if (updatedAtString) {
      // Convert the string to a JavaScript Date object
      let updatedAtDate = new Date(updatedAtString);

      // Calculate the 3rd day from the updatedAt date
      let thirdDay = new Date(updatedAtDate.getTime());
      thirdDay.setDate(updatedAtDate.getDate() + 3);

      // Calculate the 7th day from the updatedAt date
      let seventhDay = new Date(updatedAtDate.getTime());
      seventhDay.setDate(updatedAtDate.getDate() + 7);

      // Format the dates to local time in 'MM/DD/YYYY' format
      let formattedThirdDay = thirdDay.toLocaleDateString("en-US");
      let formattedSeventhDay = seventhDay.toLocaleDateString("en-US");

      // Display or use the formatted dates as needed
      console.log("3rd day from updatedAt:", formattedThirdDay);
      console.log("7th day from updatedAt:", formattedSeventhDay);
      setestimatedDate(formattedThirdDay + " - " + formattedSeventhDay);
    } else {
      console.log("Invalid updatedAt date");
    }
  }, []);
  const OrderReceived = () => {
    update_order({
      token: token,
      id: cart._id,
      body: {
        status: "COMPLETED",
        // 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
          // );
          setcompleted(true);
          setModalVisible1(false);
        } else {
          setsuccessCOD("error");
          console.log("update order failed");
        }
      })
      .catch((err) => {
        console.error(err);
      });
  };

  return (
    <TouchableOpacity
      style={styles.container}
      onPress={() => setModalVisible(true)}
    >
      <View style={styles.header}>
        <Text style={styles.headerText}>{cart.items[0].vendor_name}</Text>
        <Text style={styles.headerStatusText}>{cart.status}</Text>
      </View>
      <View style={styles.wrapper}>
        <View style={styles.prodwrapper}>
          <View style={styles.imgWrap}>
            <Image
              style={{ width: 50, height: 50, resizeMode: "cover" }}
              // source={{ uri: `${cart?.items[0].product.product_image}` }}
              source={{
                uri: `${
                  cart?.items[0].product.product_image !== ""
                    ? cart?.items[0].product.product_image
                    : "https://wkdonlinedogtraining.com/wp-content/themes/wkd-wp/build/images/bg-no-img-big.jpg"
                }`,
              }}
            />
          </View>
          <View style={styles.details}>
            <Text style={styles.text} numberOfLines={2}>
              {cart?.items[0]?.product.name}
            </Text>
            <Text style={styles.text1} numberOfLines={2}>
              Variant:{cart?.items[0].variant}
            </Text>
            <View style={styles.rateCon}>
              {cart?.items[0].price ? (
                <>
                  <View style={styles.priceCon}>
                    <Text
                      style={
                        cart?.items[0]?.sale_price
                          ? styles.textPricePromo
                          : styles.textPrice
                      }
                    >
                      ₱
                      {parseFloat(cart?.items[0].price).toLocaleString("en-US")}
                    </Text>
                  </View>
                </>
              ) : (
                <Text>No price </Text>
              )}
              <Text style={styles.text1} numberOfLines={2}>
                Quantity: {cart?.items[0].quantity}
              </Text>
            </View>
          </View>
        </View>
        <View style={styles.totalCon}>
          <View style={styles.total}></View>
          <View style={styles.total}>
            <Text style={styles.totalText}>Total: </Text>
            <Text style={styles.textPrice}>
              {" "}
              ₱
              {parseFloat(total).toLocaleString("en-US") ??
                parseFloat(cart?.total_amount).toLocaleString("en-US")}{" "}
            </Text>
          </View>
        </View>
      </View>
      {/* <View style={styles.cStatus}>
        <Text style={styles.textStatusHeader}> Status: </Text>

        <Text style={styles.textStatus}> {cart?.currentStatus}</Text>
      </View> */}
      <View style={styles.footer}>
        <Text style={styles.footerDate}>Receive by:{estimatedDate} </Text>
        {completed === false ? (
          <TouchableOpacity
            style={styles.rateBtn}
            onPress={() => setModalVisible1(true)}
          >
            <Text style={styles.rateText}>Order Receive</Text>
          </TouchableOpacity>
        ) : (
          <Text style={styles.rateText1}>Order Received</Text>
        )}
      </View>
      <Modal
        animationType="slide"
        animationIn={"zoomIn"}
        transparent={true}
        isVisible={modalVisible1}
        onSwipeComplete={() => setModalVisible1(false)}
        swipeDirection={["down", "up", "right", "left"]}
        swipeThreshold="100"
        backdropOpacity={0.2}
        style={{ margin: 0 }}
        propagateSwipe={true}
        deviceWidth={deviceWidth}
        onRequestClose={() => {
          setModalVisible1(!modalVisible1);
        }}
      >
        {/* <ReceiptCard onRequestClose={setModalVisible} cart={cart} /> */}
        <View style={styles.modalCon}>
          <Text style={styles.modalSub}>
            Note: This order will automatically be considered received 7 days
            after it is received.
          </Text>

          <Text style={styles.modalHead}>Mark as Order Received?</Text>
          <View style={styles.footerBtnWrap}>
            <TouchableOpacity
              style={styles.footerBtn}
              onPress={() => setModalVisible1(false)}
            >
              <Text style={styles.footerBtnC}>Cancel</Text>
            </TouchableOpacity>
            <TouchableOpacity
              style={styles.footerBtn}
              onPress={() => OrderReceived()}
            >
              <Text style={styles.footerBtnCo}>Confirm</Text>
            </TouchableOpacity>
          </View>
        </View>
      </Modal>
      <Modal
        animationType="slide"
        animationIn={"zoomIn"}
        transparent={true}
        isVisible={modalVisible}
        onSwipeComplete={() => setModalVisible(false)}
        swipeDirection={["down", "up", "right", "left"]}
        swipeThreshold="100"
        backdropOpacity={0.2}
        style={{ margin: 0 }}
        propagateSwipe={true}
        deviceWidth={deviceWidth}
        onRequestClose={() => {
          setModalVisible(!modalVisible);
        }}
      >
        <ReceiptCard onRequestClose={setModalVisible} cart={cart} />
      </Modal>
    </TouchableOpacity>
  );
};
const styles = StyleSheet.create({
  container: {
    // width: "95%",
    margin: 5,
    borderRadius: 10,
    borderColor: "#dddd",
    borderWidth: 1,
    overflow: "hidden",
    // flexDirection: "row",
    // padding: 10,
    backgroundColor: "#ffffff",
  },
  header: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    width: "100%",
    top: 0,
    padding: 10,
  },
  headerText: {
    fontSize: 14,
    fontWeight: "600",
  },
  headerStatusText: {
    fontSize: 14,
    fontWeight: "600",
    textTransform: "uppercase",
    color: "#ffaa00",
  },
  footer: {
    // position: "absolute",
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    bottom: 0,
    width: "100%",
  },
  imgWrap: {
    padding: 10,
  },
  wrapper: {
    margin: 10,
    marginBottom: 10,
  },
  prodwrapper: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    borderWidth: 1,
    overflow: "hidden",
    borderColor: "#dddd",
    borderRadius: 10,
    padding: 10,
  },
  priceCon: {
    flexDirection: "row",
    paddingVertical: 10,
  },
  textPrice: {
    fontSize: 14,
    fontWeight: "600",
    textTransform: "capitalize",
    color: "#ffaa00",
  },
  textPricePromo: {
    fontSize: 14,
    fontWeight: "600",
    textTransform: "capitalize",
    textDecorationLine: "line-through",
    color: "#ffaa00",
  },
  details: {
    width: "80%",
  },
  text: {
    fontSize: 13,
  },
  text1: {
    fontSize: 10,
    color: "#b4b4b4",
  },
  totalCon: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "flex-end",
    position: "relative",
    // right: 0,
    paddingTop: 10,
  },
  total: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "flex-end",
    width: "35%",
    position: "relative",
    right: 0,
  },
  totalText: {
    textAlign: "right",
  },
  cStatus: {
    backgroundColor: "#7EFFBA",
    // height: 40,
    padding: 10,
    flexDirection: "row",
    // justifyContent: "space-between",
    alignItems: "flex-end",
  },
  textStatusHeader: {
    fontSize: 12,
    fontWeight: "600",
    color: "#007938",
  },
  textStatus: {
    fontSize: 14,
    fontWeight: "400",
    color: "#007938",
  },
  rateBtn: {
    borderWidth: 2,
    overflow: "hidden",
    borderColor: "#ffaa00",
    borderRadius: 10,
    padding: 5,
    paddingHorizontal: 15,
    margin: 10,
    marginRight: 20,
  },
  rateText: {
    fontWeight: "600",
    color: "#ffaa00",
  },
  rateText1: {
    fontWeight: "600",
    color: "#ffaa00",
    padding: 10,
  },
  footerDate: {
    fontSize: 11,
    paddingLeft: 15,
    color: "#747474",
  },
  modalCon: {
    margin: 5,
    borderRadius: 10,
    borderColor: "#dddd",
    borderWidth: 1,
    overflow: "hidden",
    // flexDirection: "row",
    padding: 20,
    backgroundColor: "#ffffff",
    // height: "60%",
    justifyContent: "center",
    alignItems: "center",
  },
  footerBtnWrap: {
    flexDirection: "row",
    justifyContent: "space-between",
    width: "50%",
    marginTop: 10,
  },
  modalSub: {
    fontSize: 13,
    color: "#8f8f8f",
    fontWeight: "400",
    marginTop: 5,
  },
  modalHead: {
    fontSize: 16,

    color: "#141414",
    fontWeight: "600",
    marginVertical: 40,
  },
  footerBtn: {
    paddingHorizontal: 20,
    paddingVertical: 10,
  },
  footerBtnC: {
    color: "#ff0000",
    fontWeight: "600",
  },
  footerBtnCo: {
    color: "#0400ff",
    fontWeight: "600",
  },
});

export default ToReceiveCard;
