import React, { useEffect, useState } from "react";
import style from "./productCard.module.css";
import Image from "next/image";
import {
  ArrowDownward,
  ArrowDownwardOutlined,
  ArrowDownwardRounded,
  ArrowUpward,
  Router,
} from "@mui/icons-material";
import Loader from "@/components/utils/loader";
import { customerApi, managerApi } from "@/api/api";
import moment from "moment-timezone";
import ConfirmBox from "@/components/utils/confirmBox";
import { confirmAlert } from "react-confirm-alert";
import { createNotification } from "@/customHook/useNotification";
import SearchSelect from "../../utils/searchSelect";
import { useSelector } from "react-redux";
import InputText from "@/components/utils/inputText";
import NextImage from "@/other/NextImage";
import BtnLoader from "@/components/utils/btnLoader";
import { useRouter } from "next/router";

const ProductCard = (props) => {
  const [loader, setLoader] = useState(false);
  const [cancelLoader, setCancelLoader] = useState(false);
  const [invoicePDFBtnLoader, setInvoicePDFBtnLoader] = useState(false);
  const [returnInvoicePDFBtnLoader, setReturnInvoicePDFBtnLoader] = useState(
    []
  );
  const router = useRouter();
  const [isInvoiceAvailable, setIsInvoiceAvailable] = useState(false);
  const [returnLoader, setReturnLoader] = useState([]);
  const defaultPaymentAccepted = useSelector(
    (state) => state.generalStore.default_accepted_payment
  );
  const currencyType = useSelector((state) => state.generalStore.currency_type);
  const [paymentMethod, setPaymentMethod] = useState();
  const [paymentOptions, setPaymentOptions] = useState();
  const [bankDetails, setBankDetails] = useState({
    iban_no: "",
    account_no: "",
    account_name: "",
    bank_name: "",
    reference_no: "",
  });

  const [errorListBank, setErrorListBank] = useState({
    iban_no: false,
    account_no: false,
    account_name: false,
    bank_name: false,
    reference_no: false,
  });

  useEffect(() => {
    if (defaultPaymentAccepted && defaultPaymentAccepted.length > 0) {
      let options = [];
      for (const item of defaultPaymentAccepted) {
        options.push({ title: item.replaceAll("_", " "), value: item });
      }
      setPaymentOptions(options);
    }
  }, [defaultPaymentAccepted]);
  useEffect(() => {
    if (
      props.order.products &&
      props.order.products.length > 0 &&
      props.order.products[0].payment_accepted &&
      props.order.products[0].payment_accepted.length > 0
    ) {
      let options = [];
      for (const item of props.order.products[0].payment_accepted) {
        options.push({ title: item.replaceAll("_", " "), value: item });
      }
      setPaymentOptions(options);
    }
    console.log("props.order.product", props.order.products);
    if (props.order.products && props.order.products.length > 0) {
      let found = true;
      for (const item of props.order.products) {
        if (item.status != "return") {
          found = false;
          break;
        }
      }
      if (found === false) {
        setIsInvoiceAvailable(true);
      } else {
        setIsInvoiceAvailable(false);
      }
    }
  }, [props.order]);
  const onPendingPaymentSubmit = async (type) => {
    setLoader(true);
    if (type === "stripe") {
      await customerApi
        .post("/payment/stripe/pending", { order_id: props.order._id })
        .then((res) => {
          if (res.data.url) {
            window.location.href = res.data.url;
          }
          setLoader(false);
        })
        .catch((err) => {
          console.log(err);
          setLoader(false);
        });
    } else if (type === "paytabs") {
      await customerApi
        .post("/payment/paytabs/pending", { order_id: props.order._id })
        .then((res) => {
          if (res.data.url) {
            window.location.href = res.data.url;
          }
          setLoader(false);
        })
        .catch((err) => {
          console.log(err);
          setLoader(false);
        });
    }
  };
  const onPendingPaymentMethodSubmit = async () => {
    if (paymentMethod === "bank") {
      let errorFound = false;
      for (const item in bankDetails) {
        if (!bankDetails[item]) {
          setErrorListBank((prev) => {
            let newObject = { ...prev };
            newObject[item] = true;
            return newObject;
          });
          errorFound = true;
        } else {
          setErrorListBank((prev) => {
            let newObject = { ...prev };
            newObject[item] = false;
            return newObject;
          });
        }
      }
      if (errorFound === true) {
        createNotification("error", "Complete Required Field");
        return;
      }
    } else {
      setBankDetails();
    }
    setLoader(true);
    await customerApi
      .post("/order/place", {
        order_id: props.order._id,
        payment_method: paymentMethod,
        bank_details: bankDetails,
      })
      .then((res) => {
        if (res.data.success === true) {
          createNotification("success", "Successfully Placed Order");
          props.reload();
        }
        setLoader(false);
      })
      .catch((err) => {
        console.log(err);
        setLoader(false);
        createNotification("error", "Something Went Wrong");
      });
    setLoader(false);
  };

  const returnSubmitConfirm = (id, product_id, index) => {
    confirmAlert({
      customUI: ({ onClose }) => {
        return (
          <ConfirmBox
            onClose={onClose}
            onConfirm={() => onReturnSubmit(id, product_id, index)}
          />
        );
      },
    });
  };
  const cancelSubmitConfirm = (id) => {
    confirmAlert({
      customUI: ({ onClose }) => {
        return (
          <ConfirmBox onClose={onClose} onConfirm={() => onCancelSubmit(id)} />
        );
      },
    });
  };
  const cancelPaidSubmitConfirm = (id) => {
    confirmAlert({
      customUI: ({ onClose }) => {
        return (
          <ConfirmBox
            onClose={onClose}
            onConfirm={() => onCancelPaidSubmit(id)}
          />
        );
      },
    });
  };
  const onCancelSubmit = async (id) => {
    setCancelLoader(true);
    await customerApi
      .post("/order/cancel", { order_id: id })
      .then((res) => {
        if (res.data.success === true) {
          props.reload(true);
          createNotification("success", "Order Successfully Canceled");
        }
        setCancelLoader(false);
      })
      .catch((err) => {
        console.log(err);
        setCancelLoader(false);
        createNotification("error", "Something Went Wrong");
      });
  };
  const onCancelPaidSubmit = async (id) => {
    setCancelLoader(true);
    await customerApi
      .post("/order/paid/cancel", { order_id: id, canceled: true })
      .then((res) => {
        if (res.data.success === true) {
          props.reload(true);
          createNotification("success", "Order Successfully Canceled");
        }
        setCancelLoader(false);
      })
      .catch((err) => {
        console.log(err);
        setCancelLoader(false);
        createNotification("error", "Something Went Wrong");
      });
  };
  const downloadInvoice = async (id) => {
    try {
      setInvoicePDFBtnLoader(true);
      const response = await managerApi.get(
        "/customer/invoice/pdf?invoice_id=" + id,
        {
          responseType: "blob",
        }
      );

      console.log("response.data", response.data);
      const downloadUrl = window.URL.createObjectURL(new Blob([response.data]));
      const invoicePDF = downloadUrl;
      const link = document.createElement("a");
      link.href = invoicePDF;
      link.setAttribute("download", "invoice_" + id + ".pdf");
      document.body.appendChild(link);
      link.click();
      link.remove();

      setInvoicePDFBtnLoader(false);
    } catch (err) {
      setInvoicePDFBtnLoader(false);
      createNotification("error", "Something went wrong");
      console.log(err);
    }
  };

  const downloadReturnInvoice = async (id, index) => {
    try {
      setReturnInvoicePDFBtnLoader((prev) => {
        let newArray = [...prev];
        newArray[index] = true;
        return newArray;
      });
      const response = await managerApi.get(
        "/customer/invoice/return/pdf?invoice_id=" + id,
        {
          responseType: "blob",
        }
      );

      console.log("response.data", response.data);
      const downloadUrl = window.URL.createObjectURL(new Blob([response.data]));
      const invoicePDF = downloadUrl;
      const link = document.createElement("a");
      link.href = invoicePDF;
      link.setAttribute("download", "invoice_" + id + ".pdf");
      document.body.appendChild(link);
      link.click();
      link.remove();

      setReturnInvoicePDFBtnLoader((prev) => {
        let newArray = [...prev];
        newArray[index] = false;
        return newArray;
      });
    } catch (err) {
      setReturnInvoicePDFBtnLoader((prev) => {
        let newArray = [...prev];
        newArray[index] = false;
        return newArray;
      });
      createNotification("error", "Something went wrong");
      console.log(err);
    }
  };

  const onReturnSubmit = async (id, product_id, index) => {
    setReturnLoader((prev) => {
      let newArray = [...prev];
      newArray[index] = true;
      return newArray;
    });
    await customerApi
      .post("/order/return", { order_id: id, product_id: product_id })
      .then((res) => {
        if (res.data.success === true) {
          props.reload(true);
          createNotification("success", "Return Placed Successfully");
        }
        setReturnLoader((prev) => {
          let newArray = [...prev];
          newArray[index] = false;
          return newArray;
        });
      })
      .catch((err) => {
        console.log(err);
        setReturnLoader((prev) => {
          let newArray = [...prev];
          newArray[index] = false;
          return newArray;
        });
        createNotification("error", "Something Went Wrong");
      });
  };
  const returnEnum = ["return (processing)", "return (completed)"];
  const generateGrandTotal = (offer, price, quantity, tax, discount) => {
    let result = price;
    if (offer && offer > 0) {
      const off = (offer / 100) * result;
      result = price - off;
    }
    if (tax && tax > 0) {
      const tax_rate = (tax / 100) * result;
      result = result + tax_rate;
    }
    if (discount && discount > 0) {
      const discount_percentage = (discount / 100) * result;
      result = result - discount_percentage;
    }
    return result.toFixed(2);
  };
  const finalCal = (offer, tax, quantity, price, discount) => {
    let result = price;
    console.log("quantity: ", quantity);
    if (quantity > 0) {
      result = result * quantity;
    }
    if (offer && offer > 0) {
      const off = (offer / 100) * result;
      result = result - off;
    }
    if (tax && tax > 0) {
      const tax_rate = (tax / 100) * result;
      result = result + tax_rate;
    }
    if (discount && discount > 0) {
      const discount_percentage = (discount / 100) * result;
      result = result - discount_percentage;
    }
    return result.toFixed(2);
  };
  const [showMore, setShowMore] = useState(false);

  // Bank Details Function

  const [bank_owner_details, setBankOwnerDetails] = useState({
    iban_no: "",
    account_no: "",
    account_name: "",
    bank_name: "",
  });
  const [bankLoader, setBankLoader] = useState(false);

  const loadBank = async () => {
    setBankLoader(true);
    await customerApi
      .get("/general")
      .then((res) => {
        if (res.data.success === true) {
          setBankOwnerDetails(res.data.data.bank_details);
        }
        setBankLoader(false);
      })
      .catch((err) => {
        console.log("Err:", err);
        setBankLoader(false);
      });
  };
  return (
    <div className={`${style.product_section} ${style.box_design}`}>
      {!showMore && props.order.products.length > 1 ? (
        <>
          <div className={style.product_data_section_less}>
            {props.order.products.map((item, index) => (
              <div
                className={style.product_data}
                key={`${item}_${index}_products`}
              >
                <div
                  onClick={() =>
                    router.push(`/product/${item.slug}`)
                  }
                >
                  <div className={style.product_image}>
                    <NextImage
                      src={
                        item.image &&
                        item.image.length > 0 &&
                        process.env.NEXT_PUBLIC_UPLOADS +
                          "/products/" +
                          item.image[0]
                      }
                      className={style.nextImage}
                      alt="image"
                      fill
                    />
                  </div>

                  <div className={style.selectBox}>
                    <div>
                      Name:
                      <span className="capitalize">
                        {item &&
                          item.name &&
                          item.name
                            .replaceAll("<b>", "")
                            .replaceAll("</b>", "")
                            .replaceAll("<i>", "")
                            .replaceAll("</i>", "")
                            .replaceAll("</br>", "")}
                      </span>
                    </div>
                    <div>
                      Product Code:
                      <span>{item.product_code}</span>
                    </div>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </>
      ) : (
        props.order.products.map((item, index) => (
          <>
            <div
              className={style.product_data_section}
              key={`${item.order_id}_${item.product_id}`}
            >
              <div
                className={style.product_data}
                onClick={() =>
                  router.push(`/product/${item.slug}`)
                }
              >
                {item.image && item.image.length > 0 && item.image[0] && (
                  <div className={style.product_image}>
                    <NextImage
                      src={
                        item.image.length > 0 &&
                        process.env.NEXT_PUBLIC_UPLOADS +
                          "/products/" +
                          item.image[0]
                      }
                      alt="image"
                      fill
                    />
                  </div>
                )}
                <div className={style.selectBox}>
                  <div>
                    Name:{" "}
                    <span className="capitalize">
                      {item &&
                        item.name &&
                        item.name
                          .replaceAll("<b>", "")
                          .replaceAll("</b>", "")
                          .replaceAll("<i>", "")
                          .replaceAll("</i>", "")
                          .replaceAll("</br>", "")}
                    </span>
                  </div>
                  <div>
                    Product Code: <span>{item.product_code}</span>
                  </div>
                </div>
              </div>

              {props.order.cost > 0 && (
                <div className={style.product_price}>
                  <div className={style.purchase_detail}>
                    <div
                      className={`${style.purchase_data} ${style.color_dark}`}
                    >
                      <div className={`${style.purchase_title}`}>Qnty :</div>
                      <div
                        className={`${style.purchase_value} ${style.title_dark}`}
                      >
                        {item.quantity}
                      </div>
                    </div>
                    <div
                      className={`${style.purchase_data} ${style.color_dark}`}
                    >
                      <div className={style.purchase_title}>Price :</div>
                      <div
                        className={`${style.purchase_value} ${style.title_dark}`}
                      >
                        {item.offer ? (
                          <div className={style.total_price}>
                            {item.price}&nbsp;{currencyType}
                          </div>
                        ) : (
                          ""
                        )}
                        <div className={style.grand_total}>
                          {generateGrandTotal(
                            item.offer,
                            item.price,
                            item.quantity,
                            0,
                            0
                          )}
                          &nbsp;{currencyType}
                        </div>
                      </div>
                    </div>
                    {item.tax_rate ? (
                      <div
                        className={`${style.purchase_data} ${style.color_dark}`}
                      >
                        <div className={`${style.purchase_title}`}>Tax :</div>
                        <div
                          className={`${style.purchase_value} ${style.title_dark}`}
                        >
                          {item.tax_rate}%
                        </div>
                      </div>
                    ) : (
                      ""
                    )}

                    {item.discount_percentage &&
                    item.discount_percentage > 0 ? (
                      <div
                        className={`${style.purchase_data} ${style.color_dark}`}
                      >
                        <div className={style.purchase_title}>Discount :</div>
                        <div
                          className={`${style.purchase_value} ${style.title_dark}`}
                        >
                          <div className={style.discount_percentage}>
                            {item.discount_percentage}%
                          </div>
                        </div>
                      </div>
                    ) : (
                      ""
                    )}
                    <div
                      className={`${style.purchase_data} ${style.color_dark}`}
                    >
                      <div className={style.purchase_title}>Total :</div>
                      <div
                        className={`${style.purchase_value} ${style.title_dark}`}
                      >
                        <div className={style.grand_total}>
                          {finalCal(
                            item.offer,
                            item.tax_rate,
                            item.quantity,
                            item.price,
                            item.discount_percentage
                          )}
                          &nbsp;{currencyType}
                        </div>
                      </div>
                    </div>
                    {props.order.invoice_no &&
                      item.return_invoice_no &&
                      item.return_id &&
                      item.status === "return" &&
                      (!returnInvoicePDFBtnLoader[index] ? (
                        <button
                          className={`secondary-btn ${style.custom_secondary}`}
                          type="button"
                          onClick={() =>
                            downloadReturnInvoice(item.return_invoice_no, index)
                          }
                        >
                          Return Invoice
                        </button>
                      ) : (
                        <button
                          className={`secondary-btn ${style.custom_secondary}`}
                        >
                          <Loader className={style.downloadBntLoader} />
                        </button>
                      ))}
                    {item.status === "processed" &&
                      props.order.order_status == "completed" &&
                      props.order.delivered_date &&
                      moment()
                        .tz("Asia/Dubai")
                        .isSameOrBefore(
                          moment(props.order.delivered_date)
                            .add(item.return_period, "days")
                            .format()
                        ) && (
                        <>
                          {returnLoader[index] && (
                            <button
                              className={`primary_btn_no_animation ${style.custom_primary}`}
                            >
                              <Loader className={style.submitLoader} />
                            </button>
                          )}
                          {!returnLoader[index] && (
                            <button
                              className={`primary_btn_no_animation ${style.custom_secondary}`}
                              onClick={() =>
                                returnSubmitConfirm(
                                  props.order._id,
                                  item.product_id,
                                  index
                                )
                              }
                            >
                              Return
                            </button>
                          )}
                        </>
                      )}
                  </div>
                </div>
              )}
            </div>
          </>
        ))
      )}

      {props.order.products.length > 1 && (
        <>
          {!showMore && (
            <div
              className={style.show_more}
              onClick={() => setShowMore((prev) => !prev)}
            >
              Show More <ArrowDownward />
            </div>
          )}
          {showMore && (
            <div
              className={style.show_less}
              onClick={() => setShowMore((prev) => !prev)}
            >
              Show Less <ArrowUpward />
            </div>
          )}
        </>
      )}
      <hr />
      <div>
        Order ID : <span>{props.order._id}</span>
      </div>
      <hr />
      {paymentMethod === "bank" &&
        (bank_owner_details && bank_owner_details.iban_no ? (
          <>
            {!bankLoader &&
              bank_owner_details &&
              bank_owner_details.iban_no &&
              bank_owner_details.account_no &&
              bank_owner_details.account_name &&
              bank_owner_details.bank_name && (
                <>
                  <div className={style.bank_details}>
                    <h6>Bank Details</h6>
                    <p>
                      <b>IBAN No : </b> {bank_owner_details.iban_no}
                    </p>
                    <p>
                      <b>Account Name : </b> {bank_owner_details.account_name}
                    </p>
                    <p>
                      <b>Account No : </b> {bank_owner_details.account_no}
                    </p>
                    <p>
                      <b>Bank Name : </b> {bank_owner_details.bank_name}
                    </p>
                  </div>
                </>
              )}
            {bankLoader && (
              <div className={style.bank_details}>
                <Loader className={style.loader} />
              </div>
            )}
            <div className={style.section_data}>
              <div>
                <p>IBAN No</p>
                <InputText
                  type="text"
                  placeholder="Enter IBAN No"
                  getValue={(value) => {
                    setBankDetails((prev) => {
                      let newObject = { ...prev };
                      newObject.iban_no = value;
                      return newObject;
                    });
                    if (value) {
                      setErrorListBank((prev) => {
                        let newObject = { ...prev };
                        newObject.iban_no = false;
                        return newObject;
                      });
                    }
                  }}
                  required={true}
                  error={errorListBank.iban_no}
                  value={bankDetails.iban_no}
                  customClass={style.customInputClass}
                />
              </div>
              <div>
                <p>Account Name</p>
                <InputText
                  placeholder="Enter Account Name"
                  getValue={(value) => {
                    setBankDetails((prev) => {
                      let newObject = { ...prev };
                      newObject.account_name = value;
                      return newObject;
                    });
                    if (value) {
                      setErrorListBank((prev) => {
                        let newObject = { ...prev };
                        newObject.account_name = false;
                        return newObject;
                      });
                    }
                  }}
                  required={true}
                  error={errorListBank.account_name}
                  value={bankDetails.account_name}
                  customClass={style.customInputClass}
                />
              </div>
              <div>
                <p>Account Number</p>
                <InputText
                  type="number"
                  placeholder="Enter Account Number"
                  getValue={(value) => {
                    setBankDetails((prev) => {
                      let newObject = { ...prev };
                      newObject.account_no = value;
                      return newObject;
                    });
                    if (value) {
                      setErrorListBank((prev) => {
                        let newObject = { ...prev };
                        newObject.account_no = false;
                        return newObject;
                      });
                    }
                  }}
                  required={true}
                  error={errorListBank.account_no}
                  value={bankDetails.account_no}
                  customClass={style.customInputClass}
                />
              </div>
              <div>
                <p>Bank Name</p>
                <InputText
                  placeholder="Enter Bank Name"
                  getValue={(value) => {
                    setBankDetails((prev) => {
                      let newObject = { ...prev };
                      newObject.bank_name = value;
                      return newObject;
                    });
                    if (value) {
                      setErrorListBank((prev) => {
                        let newObject = { ...prev };
                        newObject.bank_name = false;
                        return newObject;
                      });
                    }
                  }}
                  required={true}
                  error={errorListBank.bank_name}
                  value={bankDetails.bank_name}
                  customClass={style.customInputClass}
                />
              </div>
              <div>
                <p>Payment Reference No</p>
                <InputText
                  placeholder="Enter Payment Reference No"
                  getValue={(value) => {
                    setBankDetails((prev) => {
                      let newObject = { ...prev };
                      newObject.reference_no = value;
                      return newObject;
                    });
                    if (value) {
                      setErrorListBank((prev) => {
                        let newObject = { ...prev };
                        newObject.reference_no = false;
                        return newObject;
                      });
                    }
                  }}
                  required={true}
                  error={errorListBank.reference_no}
                  value={bankDetails.reference_no}
                  customClass={style.customInputClass}
                />
              </div>
            </div>
          </>
        ) : (
          <p className={style.bankError}>Bank Details Not Available</p>
        ))}
      <div className={style.product_option_section}>
        {props.delivery_type == "pickup" ? (
          <div className={style.address_section}>
            <div className={style.address_title}>Pickup Details</div>
            <div className={`${style.address} capitalize`}>
              {props.pickup_name} <br />
              {props.pickup_address}
            </div>
          </div>
        ) : (
          <div className={style.address_section}>
            <div className={style.address_title}>Shipping Address</div>
            <div className={`${style.address} capitalize`}>
              {props.address.name} (
              {props.address.dial_code && `+${props.address.dial_code}`}
              {props.address.phone.replace(/^0+/, "")})
              <br />
              {`${props.address.address_1 && props.address.address_1} ${
                props.address.address_2 && ", " + props.address.address_2
              } ${props.address.landmark && ", " + props.address.landmark} ${
                props.address.state && ", " + props.address.state
              } ${props.address.country && ", " + props.address.country}`}
            </div>
          </div>
        )}
        {props.order.payment_status == "paid" &&
          props.order.order_status != "completed" &&
          props.order.estimated_delivery && (
            <div className={style.address_section}>
              <div className={style.address_title}>
                {props.delivery_type == "pickup" ? "Pickup" : "Delivery"}
              </div>
              <div className={style.address}>
                {props.order.estimated_delivery}
              </div>
            </div>
          )}
        {props.order.delivery_charge > 0 &&
          props.order.cost > props.order.delivery_charge && (
            <div className={style.address_section}>
              <div className={style.address_title}>Delivery Charge</div>
              <div className={style.address}>{props.order.delivery_charge}</div>
            </div>
          )}
        {props.order.cod_charge > 0 &&
          props.order.cost > props.order.cod_charge && (
            <div className={style.address_section}>
              <div className={style.address_title}>COD Charge</div>
              <div className={style.address}>{props.order.cod_charge}</div>
            </div>
          )}
        {props.order.cost > 0 &&
          props.order.cost > props.order.delivery_charge && (
            <div className={style.address_section}>
              <div className={style.address_title}>Total</div>
              <div className={style.address}>{props.order.cost}</div>
            </div>
          )}
        {props.order.payment_status && (
          <div className={style.address_section}>
            <div className={style.address_title}>Status</div>
            <div className={`${style.address} capitalize`}>
              {props.order.payment_status.replaceAll("_", " ")}
            </div>
          </div>
        )}
        {props.order.payment_accepted && (
          <div className={style.address_section}>
            <div className={style.address_title}>Payment</div>
            <div className={`${style.address} capitalize`}>
              {props.order.payment_accepted}
            </div>
          </div>
        )}
        {props.order.cost > 0 &&
        props.order.cost > props.order.delivery_charge ? (
          <div className={style.button_section}>
            <div
              className={`${style.purchase_status} capitalize ${
                props.order.status === "pending"
                  ? style.payment_pending
                  : style.delivered
              }`}
            >
              {props.order.payment_status === "not_paid" &&
              props.order.order_status === "pending"
                ? "Payment Pending"
                : props.order.order_status}
            </div>
            {props.order.payment_status != "paid" ? (
              <>
                {props.order.order_status == "pending" && (
                  <SearchSelect
                    setOption={paymentOptions}
                    placeholder={`Select Payment Method`}
                    setSearchPlaceholder={"Search"}
                    getValue={(value) => setPaymentMethod(value.value)}
                    customCss={`${style.custom_css_select}`}
                  />
                )}

                {!loader &&
                  props.order.order_status == "pending" &&
                  ["bank", "cash_on_delivery"].includes(paymentMethod) && (
                    <button
                      className={`primary_btn ${style.custom_primary}`}
                      onClick={() => onPendingPaymentMethodSubmit()}
                    >
                      Place Order
                    </button>
                  )}
                {!loader
                  ? props.order.order_status == "pending" &&
                    paymentMethod === "card(stripe)" && (
                      <button
                        className={`primary_btn ${style.custom_primary}`}
                        onClick={() => onPendingPaymentSubmit("stripe")}
                      >
                        Pay {props.order.cost}
                        &nbsp;{currencyType}
                      </button>
                    )
                  : props.order.order_status == "pending" &&
                    paymentMethod === "card(stripe)" && (
                      <button className={`primary_btn ${style.custom_primary}`}>
                        <BtnLoader className={style.payBtnLoader} />
                      </button>
                    )}
                {!loader
                  ? props.order.order_status == "pending" &&
                    paymentMethod === "card(paytabs)" && (
                      <button
                        className={`primary_btn ${style.custom_primary}`}
                        onClick={() => onPendingPaymentSubmit("paytabs")}
                      >
                        Pay {props.order.cost}
                        &nbsp;{currencyType}
                      </button>
                    )
                  : props.order.order_status == "pending" &&
                    paymentMethod === "card(paytabs)" && (
                      <button className={`primary_btn ${style.custom_primary}`}>
                        <BtnLoader className={style.payBtnLoader} />
                      </button>
                    )}
              </>
            ) : (
              <>
                {props.order.invoice_no &&
                !returnEnum.includes(props.order.order_status) &&
                !invoicePDFBtnLoader ? (
                  isInvoiceAvailable && (
                    <button
                      className={`secondary-btn ${style.custom_secondary}`}
                      type="button"
                      onClick={() => downloadInvoice(props.order.invoice_no)}
                    >
                      Download Invoice
                    </button>
                  )
                ) : (
                  <button className={`secondary-btn ${style.custom_secondary}`}>
                    <Loader className={style.downloadBntLoader} />
                  </button>
                )}
              </>
            )}
            {props.order.order_status !== "canceled" && (
              <>
                {["pending", "processing"].includes(props.order.order_status) &&
                  props.order.payment_status == "not_paid" && (
                    <>
                      {cancelLoader && (
                        <button
                          className={`secondary-btn ${style.custom_secondary}`}
                        >
                          <Loader className={style.cancelLoader} />
                        </button>
                      )}
                      {!cancelLoader && (
                        <button
                          className={`secondary-btn ${style.custom_secondary}`}
                          onClick={() => cancelSubmitConfirm(props.order._id)}
                        >
                          Cancel
                        </button>
                      )}
                    </>
                  )}
                {["pending", "processing"].includes(props.order.order_status) &&
                  props.order.payment_status == "paid" && (
                    <>
                      {cancelLoader && (
                        <button
                          className={`secondary-btn ${style.custom_secondary}`}
                        >
                          <Loader className={style.cancelLoader} />
                        </button>
                      )}
                      {!cancelLoader && (
                        <button
                          className={`secondary-btn ${style.custom_secondary}`}
                          onClick={() =>
                            cancelPaidSubmitConfirm(props.order._id)
                          }
                        >
                          Cancel
                        </button>
                      )}
                    </>
                  )}
              </>
            )}
          </div>
        ) : (
          props.order.order_status !== "canceled" && (
            <div className={style.button_section}>
              <div
                className={`${style.purchase_status} ${style.payment_pending}`}
              >
                Order Requested
              </div>
              {cancelLoader && (
                <button className={`secondary-btn ${style.custom_secondary}`}>
                  <Loader className={style.cancelLoader} />
                </button>
              )}
              {!cancelLoader && (
                <button
                  className={`secondary-btn ${style.custom_secondary}`}
                  onClick={() => cancelSubmitConfirm(props.order._id)}
                >
                  Cancel
                </button>
              )}
            </div>
          )
        )}
      </div>
    </div>
  );
};

export default ProductCard;
