import { faArrowRight, faCopy } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-native-fontawesome";
import Clipboard from "@react-native-community/clipboard";
// import Clipboard from '@react-native-clipboard/clipboard';
import { useNavigation } from "@react-navigation/native";
import React from "react";
import {
  View,
  Text,
  StyleSheet,
  Image,
  TouchableOpacity,
  Linking,
  // Clipboard,
} from "react-native";
import { get_order } from "../../../services/api/controllers/order";
import { get_product } from "../../../services/api/controllers/product";

const ReceiptCard = ({ cart }) => {
  const navigation = useNavigation();

  // Assuming cart.deliveryDate is a string like "2023-09-25T15:30:00Z"
  //   const cart = {
  //     billing_address: {
  //       billing_first_name: "Jun",
  //       billing_last_name: "Jihad",
  //       billing_company: "OBN",
  //       billing_email: "jun@example.com",
  //       billing_phone: "09876543211",
  //       billing_address_1: "123",
  //       billing_address_2: "San san st.",
  //       billing_city: "City of Makati",
  //       billing_state: "Metro Manila",
  //       billing_country: "PH",
  //     },
  //     shipping_address: {
  //       shipping_first_name: "San",
  //       shipping_last_name: "Di",
  //       shipping_company: "obn",
  //       shipping_email: "last@example.com",
  //       shipping_phone: "9876543211",
  //       shipping_address_1: "11",
  //       shipping_address_2: "San Man st.",
  //       shipping_city: "City of Makati",
  //       shipping_state: "Metro Manila",
  //       shipping_country: "PH",
  //     },
  //     payment: {
  //       details: [],
  //       status: "UNPAID",
  //       reference_number: "cDFQF1eO",
  //     },
  //     _id: "654d7aa65ce79c9883b5c2fc",
  //     customer: [
  //       {
  //         customer_id: "65379c946645ab5293b5d2e6",
  //         name: "mark sans",
  //         _id: "654d7aa65ce79c9883b5c2fd",
  //       },
  //     ],
  //     total_amount: "1500",
  //     items: [
  //       {
  //         product: {
  //           product_image:
  //             "https://api.obanana.shop/images/storage/product_uploads/watch.jpg",
  //           product_id: "65328abe915856458f05d9e4",
  //           name: "M7 ProMax Smart Watch",
  //         },
  //         price: "1500",
  //         quantity: "1",
  //         vendor_id: "6527b593f79b5deac5ad6cbc",
  //         vendor_name: "obanana.gadgetHub",
  //         _id: "654d7aa65ce79c9883b5c2fe",
  //       },
  //     ],
  //     status: "CART",
  //     createdAt: "2023-11-10T00:34:46.102Z",
  //     updatedAt: "2023-11-10T00:34:46.103Z",
  //     __v: 0,
  //     order_date: "2023-11-10T02:34:00.212Z",
  //     payment_method: "select payment method",
  //   };
  const formatTime = (utcTimestamp) => {
    // const utcTimestamp = "2023-11-10T06:00:47.789Z";
    const utcDate = new Date(utcTimestamp);

    // Convert to Philippine time (UTC+8)
    const phTime = new Date(utcDate.getTime() + 8 * 60 * 60 * 1000);

    // Format the output
    const options = {
      year: "numeric",
      month: "2-digit",
      day: "2-digit",
      hour: "2-digit",
      minute: "2-digit",
      hour12: false,
    };

    const formattedTime = phTime.toLocaleString("en-PH", options);
    return formattedTime;
  };
  const expectedShippingStartDateMin = new Date(
    cart.expectedShippingStartDateMin
  );
  const month = expectedShippingStartDateMin.toLocaleString("en-US", {
    month: "short",
  });
  const day = expectedShippingStartDateMin.getDate();
  const options = {
    year: "numeric",
    month: "short",
    day: "2-digit",
  };
  const options2 = {
    month: "short",
    day: "2-digit",
  };
  const time = expectedShippingStartDateMin.toLocaleString("en-US", {
    timeZone: "Asia/Manila",
    ...options2,
  });
  const expectedShippingStartDateMax = new Date(
    cart.expectedShippingStartDateMax
  );
  const total = parseFloat(cart?.total_amount);

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

  // 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} `;

  function formatDate(input) {
    let date;

    // Check if the input is a Unix timestamp (number) or a string
    if (
      typeof input === "number" ||
      (typeof input === "string" && !isNaN(Number(input)))
    ) {
      date = new Date(Number(input) * 1000); // Convert string to number and then to milliseconds
    } else if (typeof input === "string") {
      date = new Date(input); // Try to create a Date object from the string
    } else {
      return "Invalid input";
    }

    // Check if the date is valid
    if (isNaN(date.getTime())) {
      return "Invalid date";
    }

    // Convert to local time
    const localDate = date.toLocaleString("en-PH", {
      timeZone: "Asia/Manila",
      year: "numeric",
      month: "2-digit",
      day: "2-digit",
      hour: "2-digit",
      minute: "2-digit",
      hour12: false,
    });

    return localDate;
    // .replace(",", ""); // Removing the comma from the default format
  }

  // Test cases
  console.log(
    formatDate(
      cart?.payment?.details[0]?.attributes?.updated_at ?? ""
      // "2023-10-23T05:54:34.525Z"
    )
  ); // Output: 10/23/2023, 13:55 (Philippines Time)
  console.log(formatDate(1699934532)); // Output: 10/23/2023, 13:55 (Philippines Time)
  console.log(formatDate("2023-10-23T05:54:34.525Z")); // Output: 10/23/2023, 13:54 (Philippines Time)

  // const getProd = (idP) => {
  //   console.log(idP);
  //   get_product({
  //     id: idP,
  //   })
  //     .then((result) => {
  //       //  console.log("result" + result);

  //       if (result.error) {
  //         setError(result.error);
  //       } else {
  //         // setcart(result.data);
  //         navigation.navigate("Product", { product: result.data });
  //         console.log(result.data);
  //       }
  //     })
  //     .catch((error) => {
  //       setError(error.message);
  //     })
  //     .finally(() => {
  //       // setprodIsLoading(false); // Set loading to false when done loading
  //     });
  // };
  const getProd = (idP) => {
    console.log(idP);
    get_product({
      id: idP,
    })
      .then((result) => {
        //  console.log("result" + result);
        if (result.error) {
          // setError(result.error);
        } else if (result.data.product_type === "variation") {
          get_product({
            id: result.data.parent_id,
          })
            .then((result1) => {
              //  console.log("result" + result);

              if (result1.error) {
                // setError(result1.error);
              } else {
                // setcart(result.data);
                navigation.navigate("Product", { product: result1.data });
                console.log(result1.data);
              }
            })
            .catch((error) => {
              // setError(error.message);
            })
            .finally(() => {
              // set
            });
        } else {
          //  else {
          // setcart(result.data);
          navigation.navigate("Product", { product: result.data });
          console.log(result.data);
          // }
        }
      })
      .catch((error) => {
        // setError(error.message);
        console.log("mm " + idP);
      })
      .finally(() => {
        // setprodIsLoading(false); // Set loading to false when done loading
      });
  };
  const copyToClipboard = () => {
    Clipboard.setString('text');
  };
  return (
    <View style={styles.container}>
      <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}>
        <TouchableOpacity
          style={styles.prodwrapper}
          onPress={() => getProd(cart?.items[0]?.product?.product_id)}
        >
          <View style={styles.imgWrap}>
            <Image
              style={{ width: 50, height: 50, resizeMode: "cover" }}
              source={{ uri: `${cart?.items[0].product.product_image}` }}
            />
          </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>
        </TouchableOpacity>
        <View style={styles.totalCon}>
          <View style={styles.total}></View>
          <View style={styles.total}>
            {/* <Text style={styles.totalText}>Total: </Text>
            <Text style={styles.textPrice}>
              {" "}
              ₱{total.toFixed(2) ?? cart?.total_amount}{" "}
            </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.tableCon}>
        <View style={styles.tableWrap}>
          <View style={styles.tableConRight}>
            <Text style={styles.tableRightText}>Merch Total:</Text>
            <Text style={styles.tableRightText}>Shipping Fee:</Text>
            {/*  <Text style={styles.tableRightText}>Handling Fee:</Text> */}
            <Text style={styles.tableRightTextBold}>Order Total:</Text>
          </View>
          <View style={styles.tableConLeft}>
            <Text style={styles.tableLeftText}>
              ₱
              {parseFloat(cart?.items[0].price).toLocaleString("en-US") ??
                parseFloat(cart?.items[0].price).toLocaleString("en-US")}{" "}
            </Text>
            <Text style={styles.tableLeftText}>
              ₱
              {cart?.shipping_fee
                ? parseFloat(cart?.shipping_fee).toLocaleString("en-US")
                : 50.0}
            </Text>
            {/*   <Text style={styles.tableLeftText}>₱0.00</Text> */}
            <Text style={styles.tableLeftTextBold}>
              ₱
              {parseFloat(total).toLocaleString("en-US") ??
                parseFloat(cart?.total_amount).toLocaleString("en-US")}{" "}
            </Text>
          </View>
        </View>
      </View>
      <View style={styles.tableCon}>
        <View style={styles.tableWrap}>
          <View style={styles.tableConRight}>
            <Text style={styles.tableRightText}>Payment Method:</Text>
            {cart?.status === "TO RECEIVE" ||
            cart?.status === "To Receive" ||
            cart?.status === "COMPLETED" ||
            cart?.status === "Completed" ? (
              <>
                <Text style={styles.tableRightText}>Shipping Courier:</Text>
                <Text style={styles.tableRightText}>Tracking Number:</Text>
              </>
            ) : null}
          </View>
          <View style={styles.tableConLeft}>
            <Text style={styles.tableLeftText}>{cart?.payment_method}</Text>
            {cart?.status === "TO RECEIVE" ||
            cart?.status === "To Receive" ||
            cart?.status === "COMPLETED" ||
            cart?.status === "Completed" ? (
              <>
                <Text style={styles.tableLeftText1}>{cart?.courier_name}</Text>
                <Text style={styles.tableLeftText1}>
                  {cart?.tracking_number}
                  {/* <TouchableOpacity
                    onPress={() => copyToClipboard()}
                  >
                    <FontAwesomeIcon
                      icon={faCopy}
                      color={"#ffaa00"}
                      size={18}
                      style={{
                        paddingHorizontal: 33,
                      }}
                    />
                  </TouchableOpacity> */}
                </Text>
              </>
            ) : null}
          </View>
        </View>
      </View>
      {cart?.status === "TO RECEIVE" ||
      cart?.status === "To Receive" ||
      cart?.status === "COMPLETED" ||
      cart?.status === "Completed" ? (
        <TouchableOpacity
          style={styles.cLink}
          onPress={() => {
            Linking.openURL(`${cart?.courier_url}`);
          }}
        >
          <Text style={styles.textStatusHeader}>Track your parcel here</Text>

          <FontAwesomeIcon
            icon={faArrowRight}
            color={"#ffaa00"}
            size={18}
            style={{
              paddingHorizontal: 33,
            }}
          />
        </TouchableOpacity>
      ) : null}

      <View style={styles.tableCon}>
        <View style={styles.tableWrap}>
          <View style={styles.tableConRight}>
            <Text style={styles.tableRightText}>Order ID:</Text>
            <Text style={styles.tableRightText}>Order Time:</Text>
            {cart?.status === "TO SHIP" || cart?.status === "To Ship" ? (
              <Text style={styles.tableRightText}>Payment Time:</Text>
            ) : null}
            {cart?.status === "TO RECEIVE" || cart?.status === "To Receive" ? (
              <Text style={styles.tableRightText}>Ship Time:</Text>
            ) : null}

            {cart?.status === "COMPLETED" || cart?.status === "Completed" ? (
              <Text style={styles.tableRightText}>Completed Time:</Text>
            ) : null}
          </View>
          <View style={styles.tableConLeft1}>
            <Text style={styles.tableLeftText1}>{cart?._id} </Text>
            <Text style={styles.tableLeftText1}>
              {formatDate(cart?.order_date)}
            </Text>
            {cart?.status === "TO SHIP" || cart?.status === "To Ship" ? (
              <Text style={styles.tableLeftText1}>
                {cart?.payment_method !== "Cash On Delivery"
                  ? formatDate(
                      cart?.payment?.details[0]?.attributes?.updated_at ?? ""
                    )
                  : "no date yet"}
              </Text>
            ) : null}
            {cart?.status === "TO RECEIVE" || cart?.status === "To Receive" ? (
              <Text style={styles.tableLeftText1}>
                {cart?.shipping?.shipping_date
                  ? formatDate(cart?.shipping?.shipping_date ?? "")
                  : "no date yet"}
              </Text>
            ) : null}

            {cart?.status === "COMPLETED" || cart?.status === "Completed" ? (
              <Text style={styles.tableLeftText1}>
                {cart?.status === "COMPLETED"
                  ? formatTime(cart?.shipping?.delivery_date)
                  : "no date yet"}
              </Text>
            ) : null}
          </View>
        </View>
      </View>
      <View style={styles.tableCon}>
        <View
          style={{
            flexDirection: "row",
            justifyContent: "space-between",
            width: "95%",
          }}
        >
          <Text style={styles.tableRightTextBold}>Shipping Address:</Text>
          <Text style={styles.tableRightTextBold}></Text>
        </View>
        <Text style={styles.listItemTexteta} numberOfLines={4}>
          {cart.shipping_address?.shipping_address_1 +
            " " +
            cart.shipping_address?.shipping_address_2 +
            ", " +
            cart.shipping_address?.shipping_barangay +
            ", " +
            cart.shipping_address?.shipping_city +
            ", " +
            cart.shipping_address?.shipping_state +
            " "}
          {cart.shipping_address?.shipping_country === "PH"
            ? "Philippines"
            : cart.shipping_address?.shipping_country}
        </Text>
      </View>

      <View style={styles.footer}>
        {/* <Text style={styles.footerDate}>
          Ship by: {time} - {time2}{" "}
        </Text> */}

        <TouchableOpacity style={styles.rateBtn}>
          {/* <Text style={styles.rateText}> Rate</Text> */}
        </TouchableOpacity>
      </View>
    </View>
  );
};
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",
    // backgroundColor: "#e6e6e6",

    // height: 40,
    padding: 10,
    flexDirection: "row",
    // justifyContent: "space-between",
    alignItems: "flex-end",
  },
  cLink: {
    // backgroundColor: "#7EFFBA",
    backgroundColor: "#ffffff",
    borderWidth: 1,
    borderColor: "#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: "#fffefd",
    borderRadius: 10,
    padding: 5,
    paddingHorizontal: 15,
    margin: 10,
    marginRight: 20,
  },
  rateText: {
    fontWeight: "600",
    color: "#ff3c00",
  },
  tableCon: {
    justifyContent: "space-between",
    alignItems: "center",
    padding: 10,
    borderBottomWidth: 1,
    borderColor: "#dddd",
  },
  tableWrap: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    width: "100%",
    width: "95%",
  },
  tableConLeft: {
    width: "40%",
  },
  tableConLeft1: {
    width: "60%",
  },
  tableLeftText: {
    textAlign: "left",
    fontSize: 13,
    padding: 10,

    // fontWeight: "600",
    color: "#ffaa00",
  },
  tableLeftText1: {
    textAlign: "left",
    fontSize: 13,
    padding: 10,

    // fontWeight: "600",
    // color: "#ffaa00",
  },
  tableLeftTextBold: {
    fontSize: 13,
    fontWeight: "600",
    color: "#ffaa00",
    padding: 10,
  },
  tableConRight: {
    width: "40%",
  },
  tableRightText: {
    fontSize: 13,
    textAlign: "left",

    // fontWeight: "600",
    color: "#8d8d8d",
    padding: 10,
  },
  tableRightTextBold: {
    fontSize: 13,
    fontWeight: "600",
    color: "#505050",
    padding: 10,
  },
  footerDate: {
    fontSize: 11,
    paddingLeft: 15,
    color: "#747474",
  },
});

export default ReceiptCard;
