import React, { useState, useEffect, FC, useContext } from "react";
import Router, { useRouter } from "next/router";
import MediaQuery, { useMediaQuery } from "react-responsive";
import cx from "classnames";
import styles from "./shoppingCart.module.scss";
import Invoice from "../Invoice/Invoice";
import {
  PlusOutlined,
  MinusOutlined,
  DeleteOutlined,
  DeleteFilled,
  LoadingOutlined,
} from "@ant-design/icons";
import {
  Button,
  Checkbox,
  Image,
  Input,
  Modal,
  notification,
  Popconfirm,
  Radio,
  Select,
  Space,
  Spin,
} from "antd";
const antIcon = <LoadingOutlined style={{ fontSize: 24 }} spin />;
import _, { get } from "lodash";
import OTPModal from "../modal/otpModal/OTPModal";
import shopConetxt from "../../context/shopConetxt";
import Link from "next/link";
import * as CartApi from "../../pages/api/cart";
import * as CommonApi from "../../pages/api/common";
import type { RadioChangeEvent } from "antd";
import { baseUrl, s3BucketUrl } from "../../constants/urls";
import NewModalSignIn from "../modal/newModalSignIn/NewModalSignIn";
import { BaseCal, GstCal } from "../../constants/commonFunction";
import { createBreadcrumb, getFlattenCategory } from "../globalUtils/utils";
import GiftSheetModal from "../modal/giftSheetModal/GiftSheetModal";
import { getIdForCartUpdate } from "../../utils/cartUtils/cartUpdateUtils";
import { LeftOutlined } from "@ant-design/icons";
import {
  updateGiftSheetApi,
  uploadGiftSheetApi,
} from "../../pages/api/productDetails/uploadGiftSheet";
const Cart: FC<any> = ({
  product,
  moveWishList,
  decreaseQuantity,
  increaseQuantity,
  deleteCartItem,
  productInvoice,
  changeDeliveryType,
  loadingIncreament,
  setLoadingIncreament,
  updateQuantity,
  stateArray,
  emptyCart,
  selectedProducts,
  handleCheckboxChange,
  deleteSelectCartItem
}) => {
  const isMobile = useMediaQuery({ maxWidth: 767.68 });
  const [loading, setLoading] = useState(false);
  // const [loadingIncreament,setLoadingIncreament] = useState(false);
  const {
    cart,
    setCartItems,
    deliveryOptions,
    setCategoryBreadcrumb,
    categoryTreeNested,
  } = useContext(shopConetxt);
  const router = useRouter();
  const [isOTPModalVisible, setIsOTPModalVisible] = useState(false);
  const [code, setCode] = useState("");
  const [oldCode, setOLdCode] = useState("");
  const [loginRes, setLoginRes] = useState<any>({});
  const [delivery, setDelivery] = useState("regularDelivery");
  const [isCouponApply, setIsCouponApply] = useState(false);
  const [productInvoiceData, setProductInvoiceData] = useState(productInvoice);
  const [selectedDeliveryDetails, setSelectedDeliveryDetails] = useState(0);
  const [isMobileOTPModalVisible, setIsMobileOTPModalVisible] = useState(false);
  const [isButtonDisable, setIsButtonDisable] = useState(false);
  const [isOfferModal, setIsOfferModal] = useState(false);
  const [offersArray, setOffersArray] = useState<any>([]);
  const [prod, setProd] = useState<any>({});
  const [isGiftModal, setIsGiftModal] = useState(false);
  const [giftSheetExcel, setGiftSheetExcel] = useState<any>(null);
  const indiDelivery = [deliveryOptions && deliveryOptions[2]];
  const continueShopping = () => {
    router.push({
      pathname: `/home`,
    });
  };

  

  useEffect(() => {
    const val: any = localStorage.getItem("loginDetails");
    const details = JSON.parse(val);

    setLoginRes(details);
    setProductInvoiceData(productInvoice);

    setCode(productInvoice?.coupon_code);
    if (productInvoice?.coupon_code) {
      setIsCouponApply(true);
    }
    CommonApi.getRequest(`${baseUrl}/api/get-coupons`).then((res) => {
      setOffersArray(res?.data?.data);
    });
  }, []);

  useEffect(() => {
    setProductInvoiceData(productInvoice);
    setCode(productInvoice?.coupon_code);
    if (productInvoice?.coupon_code) {
      setIsCouponApply(true);
    }
  }, [productInvoice]);

  const checkOut = () => {
    const val: any = localStorage.getItem("loginDetails");
    const details = JSON.parse(val);
    if (_.isEmpty(details)) {
      setIsOTPModalVisible(true);
    } else {
      setIsButtonDisable(true);
      Router.push("/checkout");
    }
  };

  const backRoute = () => {
    router.back();
  };

  const applyCuppon = (code: any) => {
    setCode(code);
    const tokenData: any = !_.isEmpty(loginRes) ? loginRes.token : null;
    const params = {
      token: tokenData,
      code: code,
    };
    if (code !== oldCode) {
      CartApi.applyCoupon(params).then((res) => {
        if (res.success === true) {
          setIsCouponApply(true);
          setOLdCode(code);
          notification.success({
            message: res.message,
          });
          CartApi.cartFetch(tokenData).then((res_cart) => {
            setProductInvoiceData(res_cart.data);
          });
        } else {
          notification.error({
            message: "Failed",
            description: res.message,
          });
        }
      });
    } else {
      notification.error({ message: "Coupon Already Applied" });
    }
  };

  const removeCoupon = () => {
    const tokenData: any = !_.isEmpty(loginRes) ? loginRes.token : null;

    CartApi.removeCoupon(tokenData).then((res) => {
      if (res.success === true) {
        setIsCouponApply(false);
        setCode("");
        setOLdCode("");
        notification.success({
          message: "Success",
          description: res.message,
        });
        CartApi.cartFetch(tokenData).then((res_cart) => {
          setProductInvoiceData(res_cart.data);
        });
      } else {
        notification.error({
          message: "Failed",
          description: res.message,
        });
      }
    });
  };

  const bredCrumb = (prod: any) => {
    // const flattenCategory = getFlattenCategory(categoryTreeNested);
    // const breadCrumbData = createBreadcrumb(
    //   prod.last_category,
    //   flattenCategory
    // );
    // setCategoryBreadcrumb(breadCrumbData);
  };

  const sumCal = (price: any, tax: any, ship: any) => {
    const finalVal: any = ship == "NA" ? "0" : `${ship}`;
    const returnVal: any =
      parseFloat(price) + parseFloat(tax) + parseFloat(finalVal);
    return parseFloat(returnVal).toFixed(2);
  };

  const uploadGiftSheet = () => {
    setIsGiftModal(false);
    updateGiftSheet(prod, giftSheetExcel);
  };

  const updateGiftSheet = async (prod: any, sheet: any) => {
    setLoading(true);
    const prod_id = getIdForCartUpdate(
      get(prod, "additional.product_id"),
      cart
    );
    const tokenData: any = !_.isEmpty(loginRes) ? loginRes.token : null;
   
    const finalPayload = {
      id: prod?.additional?.gift_sheet?.id,
      gift_sheet: sheet,
      cart_item_id: prod_id,
      token: tokenData,
    };
    await updateGiftSheetApi(finalPayload).then((res) => {
      if (res?.status) {
        //gift_sheet = res?.gift_sheet;

        CartApi.cartFetch(tokenData).then((res_cart) => {
          setProductInvoiceData(res_cart.data);
        });
      }
    });
  };

  const handleGiftSheetUpdate = (product: any) => {
    setIsGiftModal(true);
    setProd(product);
  };

  return (
    <>
      <Button
        className={cx("mx-10", styles.buckButton)}
        style={{ fontSize: "20px",cursor:"pointer",alignItems:"center",justifyContent:"center",display:'flex' }}
        type="link"
        onClick={backRoute}
        icon={<LeftOutlined />}
      >
         
        Back
      </Button>
      {/* <Button   className={cx(styles.continueShoppingButton,"mx-20")} style={{width:"100px"}} onClick={backRoute}>Back</Button> */}
      {/* <div className="px-10"  style={{border:"1px solid "}}></div> */}
      {cart.length > 0 ? (
        <div>
          <div
            className={cx(
              "flex  justify-between mt-20 pl-8",
              styles.cartPageContainer
            )}
          >
            <div className={cx(styles.cartContainer, "mx-1")}>
              <div className="flex items-center">
                <div>
                  <span className={styles.cartHeader}>My Cart</span>
                  <span className={cx("ml-2", styles.textSecondary)}>
                    ({cart.length} items)
                  </span>
                </div>
                <Popconfirm
                  title={"Are you sure you want to delete cart items?"}
                  onConfirm={emptyCart}
                  okText="Yes"
                  cancelText="Cancel"
                >
                  {cart.length == 0 ? null : (
                    <Button danger type="text">
                      {"Cart Empty"}
                    </Button>
                  )}
                </Popconfirm>
                {selectedProducts.length>0?<Popconfirm
                  title={"Are you sure you want to delete cart items?"}
                  onConfirm={deleteSelectCartItem}
                  okText="Yes"
                  cancelText="Cancel"
                >
                  {cart.length == 0 ? null : (
                    <Button danger type="text">
                      {"Delete Selected Cart Items"}
                    </Button>
                  )}
                </Popconfirm>:null}
              </div>
              {cart.length > 0 ? (
                cart.map((product: any, index: any) => {
                  return (
                    <div key={index} className={styles.cartItemCard}>
                       <Checkbox
            checked={selectedProducts.includes(product)}
            onChange={() => handleCheckboxChange(product)}
          />
                      <div className={styles.cartItemSubContainer}>
                        <div className="flex">
                          <Link
                            href={`/products/details/${product.product.url_key}-${product.product.id}`}
                          >
                            <a
                              onClick={() => {
                                bredCrumb(product);
                              }}
                            >
                              <img
                                className={cx("mr-4", styles.productImageList)}
                                src={
                                  s3BucketUrl +
                                  product?.product?.base_image?.path
                                }
                              />
                            </a>
                          </Link>
                          <div className={styles.mobileCartNameView}>
                            <Link
                              href={`/products/details/${product.product.url_key}-${product.product.id}`}
                            >
                              <a
                                onClick={() => {
                                  bredCrumb(product);
                                }}
                              >
                                <div className={styles.cartProductName}>
                                  {product?.name}
                                </div>
                              </a>
                            </Link>
                            <div
                              className={cx("mb-2", styles.cartProductDesc)}
                            ></div>
                            <div
                              className={cx(
                                "flex items-center",
                                styles.cartItemDetails
                              )}
                            >
                              <div className={styles.deleteContainer}>
                                <div className="flex items-center pr-2">
                                  <div
                                    className={cx(
                                      "flex items-center mr-2",
                                      styles.itemCountWrapper
                                    )}
                                  >
                                    <Button
                                      className={styles.plusMinusIcon}
                                      type="text"
                                      disabled={
                                        parseInt(product.additional.moq) >=
                                          product.quantity ||
                                        product.additional.change_quantity ==
                                          false
                                          ? true
                                          : false
                                      }
                                      icon={<MinusOutlined />}
                                      onClick={() => {
                                        decreaseQuantity(product);
                                      }}
                                    />
                                    <div className="flex">
                                      <Input
                                        style={{
                                          width: "50px",
                                          borderRadius: "0",
                                        }}
                                        value={product.quantity}
                                        onKeyDown={(e: any) => {
                                          console.log(e, "e");
                                          if (e.key === "Enter") {
                                            updateQuantity(e, product);
                                          }
                                        }}
                                        onChange={(e: any) => {
                                          updateQuantity(e, product);
                                        }}
                                        disabled={
                                          product.additional.change_quantity ==
                                          false
                                            ? true
                                            : false
                                        }
                                      ></Input>
                                    </div>
                                    <Button
                                      className={styles.plusMinusIcon}
                                      type="text"
                                      icon={<PlusOutlined />}
                                      disabled={
                                        product.additional.change_quantity ==
                                        false
                                          ? true
                                          : false
                                      }
                                      onClick={() => {
                                        increaseQuantity(product);
                                      }}
                                    />
                                  </div>
                                </div>
                                <Popconfirm
                                  title={
                                    "Are you sure you want to remove this item from the cart?"
                                  }
                                  onConfirm={() => {
                                    deleteCartItem(product);
                                  }}
                                  onCancel={() => {
                                    moveWishList(product);
                                  }}
                                  okText="Delete"
                                  cancelText="Move to Wishlist"
                                >
                                  <DeleteOutlined
                                    className={styles.deleteIcon}
                                  />
                                </Popconfirm>
                              </div>
                              <div>
                                <MediaQuery minWidth={769}>
                                  <Radio.Group
                                    value={parseInt(
                                      product.additional.shipping_type
                                    )}
                                    style={{ marginLeft: "1rem" }}
                                    onChange={(e) =>
                                      changeDeliveryType(e, product)
                                    }
                                    disabled={
                                      product?.additional?.product_id ==
                                        368707 ||
                                      product?.additional?.product_id ==
                                        368706 ||
                                      product?.additional?.product_id ==
                                        368708 ||
                                      product?.additional?.product_id == 368709
                                        ? true
                                        : false
                                    }
                                  >
                                    <Space
                                      direction="horizontal"
                                      style={{ columnGap: "1px !important" }}
                                    >
                                      {Object.keys(
                                        product?.additional?.gift_sheet || {}
                                      ).length !== 0
                                        ? indiDelivery &&
                                          indiDelivery.map(
                                            (deliveryDetails: any) => (
                                              <Radio key={2} value={2}>
                                                <div
                                                  className={
                                                    styles.deliveryDetails
                                                  }
                                                >
                                                  {deliveryDetails?.label}
                                                  {/* {product.additional.shipping_type===`${index}`?product.additional.estimated_delivery_days + "days":null} */}
                                                </div>
                                              </Radio>
                                            )
                                          )
                                        : deliveryOptions &&
                                          deliveryOptions.map(
                                            (
                                              deliveryDetails: any,
                                              index: number
                                            ) => (
                                              <Radio key={index} value={index}>
                                                <div
                                                  className={
                                                    styles.deliveryDetails
                                                  }
                                                >
                                                  {deliveryDetails?.label}
                                                  {/* {product.additional.shipping_type===`${index}`?product.additional.estimated_delivery_days + "days":null} */}
                                                </div>
                                              </Radio>
                                            )
                                          )}
                                    </Space>
                                  </Radio.Group>
                                </MediaQuery>
                                {/* <Select
                          className={styles.searchDropdown}
                          onChange={(value) => setDelivery(value)}
                          value={delivery}
                        >
                          <Select.Option value={"regularDelivery"}>
                            <div className={styles.divDate}>
                              Regular Delivery{" "}
                              <p className={styles.spanDate}>
                                Deliver as on 05-01-2022
                              </p>
                            </div>
                          </Select.Option>

                          <Select.Option value="lighteningDelivery">
                            <div className={styles.divDate}>
                              {" "}
                              Lightening Delivery{" "}
                              <p className={styles.spanDate}>
                                Deliver as on 05-01-2022
                              </p>
                            </div>
                          </Select.Option>
                        </Select> */}
                              </div>
                            </div>
                          </div>
                        </div>
                        <MediaQuery maxWidth={768}>
                          <Radio.Group
                            value={parseInt(product.additional.shipping_type)}
                            style={{ marginTop: "1rem" }}
                            onChange={(e) => changeDeliveryType(e, product)}
                            disabled={
                              product?.additional?.product_id == 368707 ||
                              product?.additional?.product_id == 368706 ||
                              product?.additional?.product_id == 368708 ||
                              product?.additional?.product_id == 368709
                                ? true
                                : false
                            }
                          >
                            <Space
                              direction="horizontal"
                              style={{ columnGap: "1px !important" }}
                            >
                              {Object.keys(
                                product?.additional?.gift_sheet || {}
                              ).length !== 0
                                ? indiDelivery &&
                                  indiDelivery.map((deliveryDetails: any) => (
                                    <Radio key={2} value={2}>
                                      <div className={styles.deliveryDetails}>
                                        {deliveryDetails?.label}
                                        {/* {product.additional.shipping_type===`${index}`?product.additional.estimated_delivery_days + "days":null} */}
                                      </div>
                                    </Radio>
                                  ))
                                : deliveryOptions &&
                                  deliveryOptions.map(
                                    (deliveryDetails: any, index: number) => (
                                      <Radio key={index} value={index}>
                                        <div className={styles.deliveryDetails}>
                                          {deliveryDetails?.label}
                                          {/* {product.additional.shipping_type===`${index}`?product.additional.estimated_delivery_days + "days":null} */}
                                        </div>
                                      </Radio>
                                    )
                                  )}
                            </Space>
                          </Radio.Group>
                        </MediaQuery>
                        <div className={styles.itemPricingContainer}>
                          <div className={cx("flex justify-between")}>
                            <div className={styles.itemPricingLeftCol}>
                              Price
                            </div>
                            <span className={styles.itemPricingRightCol}>
                              {product.formated_base_total}
                              {/* ₹{BaseCal(18, parseInt(product.base_total))} */}
                            </span>
                          </div>
                          <div className={cx("flex justify-between")}>
                            <div className={styles.itemPricingLeftCol}>
                              GST@ {product?.additional?.gst}%
                            </div>
                            <span className={styles.itemPricingRightCol}>
                              {/* ₹{GstCal(18, parseInt(product.base_total))} */}
                              {product.formated_tax_amount}
                            </span>
                          </div>
                          {/* <div className={cx("flex justify-between")}>
                          <div className={styles.itemPricingLeftCol}>
                            (Shipping Charges
                          </div>
                          <span className={styles.itemPricingRightCol}>
                            
                            ₹{product?.additional?.shipCharge})
                          </span>
                        </div> */}
                          {/* <div className={cx("flex justify-between")}>
                          <div className={styles.itemPricingLeftCol}>
                            Promotional Discount
                          </div>
                          <span className={styles.itemPricingRightCol}>
                            {product?.formated_discount_amount}
                          </span>
                        </div> */}
                          {/* <div className={cx("flex justify-between")}>
                          <div className={styles.itemPricingLeftCol}>
                            Other Charges
                          </div>
                          <span className={styles.itemPricingRightCol}></span>
                        </div> */}
                          <div className={cx("flex justify-between mt-2")}>
                            <div className={styles.itemPricingLeftCol}>
                              Total Amount
                            </div>
                            <span className={styles.itemPricingTotal}>
                              {product.formated_total}
                              {/* ₹{sumCal(product.base_price , product.base_tax_amount , product.additional.shipCharge)} */}
                            </span>
                          </div>
                        </div>
                      </div>
                      {Object.keys(product?.additional?.gift_sheet || {})
                        .length !== 0 && (
                        <div className="flex justify-between">
                          <span style={{ color: "red", alignSelf: "center" }}>
                            Note: The product will be sent to the address
                            mentioned in the sheet
                          </span>
                          <span className="flex justify-between self-center">
                            <span
                              className="text-ellipsis overflow-hidden self-center w-2/5 mx-3"
                              title={
                                giftSheetExcel?.name ||
                                product?.additional?.gift_sheet?.title
                              }
                            >
                              {giftSheetExcel?.name ||
                                product?.additional?.gift_sheet?.title}
                            </span>
                            <Button
                              type="primary"
                              onClick={() => handleGiftSheetUpdate(product)}
                            >
                              Update
                            </Button>
                          </span>
                        </div>
                      )}
                    </div>
                  );
                })
              ) : (
                <div
                  className={cx(
                    styles.cartEmpty,
                    "align-center justify-center"
                  )}
                >
                  Cart Item Not Available
                </div>
              )}
            </div>
            <div>
              <div className="m-2">
                <Invoice details={productInvoiceData} />
              </div>
              <div className={cx("m-2", styles.offerContainer)}>
                <div
                  className={cx("text-center mt-2 mb-4", styles.sectionHeader)}
                >
                  Offers Available
                </div>
                <div className="flex py-4"></div>
                {isCouponApply ? (
                  <div className={styles.codeContainer}>
                    <div className={styles.applyCode}>{code}</div>
                    <div className={styles.codeRemove} onClick={removeCoupon}>
                      Remove
                    </div>
                    {/* {isCouponApply ? (
              <div className={styles.applyCode}>
                Apply Code {code}{" "}
                <DeleteFilled
                  className={styles.codeRemove}
                  onClick={removeCoupon}
                />
              </div>
            ) : null} */}
                  </div>
                ) : null}

                {/* <div className={styles.offerCard}>
            <div
              className={cx(
                "flex justify-between items-center p-4",
                styles.offerCardHeader
              )}
            >
              <div>DEAL500</div>
              <Button type="primary">Apply Now</Button>
            </div>
            <div className={cx("p-4", styles.textSecondary)}>
              Flat 3% Off or Up to Rs. 500 on prepaid orders only.
            </div>
          </div> */}
                <div className={styles.scrollContainer}>
                  {offersArray.map((offer: any, idx: number) => {
                    return (
                      <div className={styles.mainCardOffer} key={idx}>
                        <div
                          className={styles.rowCardOffer}
                          onClick={() => {
                            applyCuppon(offer?.code);
                          }}
                        >
                          <div>
                            <div className={styles.codeOffer}>
                              {offer?.name}
                            </div>
                            <div className={styles.descriptionOffer}>
                              {offer?.description}
                            </div>
                          </div>
                          <div>
                            <div
                              className={styles.buttonOffer}
                              // onClick={() => {
                              //   applyCuppon(offer?.code);
                              // }}
                            >
                              APPLY
                            </div>
                            <div className={styles.useCodeOffer}>
                              <div className={styles.useCodeText}>Use Code</div>
                              <div className={styles.useCode}>
                                {offer?.code}
                              </div>
                            </div>
                            {/* <div className={styles.tcOffer}>T&C Apply</div> */}
                          </div>
                        </div>
                      </div>
                    );
                  })}
                </div>
              </div>
            </div>
          </div>
          <Spin
            indicator={antIcon}
            spinning={loadingIncreament}
            className={styles.loaderContainer}
          />
          <div
            className={cx(
              "flex justify-between w-full px-12 pb-12 pt-4",
              styles.stickyCartFooter
            )}
          >
            <Button
              className={styles.continueShoppingButton}
              onClick={() => {
                continueShopping();
              }}
            >
              <div className="flex items-center justify-center">
                <PlusOutlined />
                <div className="pl-2">Continue Shopping</div>
              </div>
            </Button>
            <Button
              disabled={isButtonDisable}
              onClick={() => {
                checkOut();
              }}
              className={styles.placeOrderButton}
              type="primary"
            >
              Place Order
            </Button>
          </div>

          <OTPModal
            handleOTPClose={() => {
              setIsOTPModalVisible(false);
            }}
            page={"checkOut"}
            isOTPModalVisible={isOTPModalVisible}
            stateArray={stateArray}
          />
          <NewModalSignIn
            handleMobileClose={() => {
              setIsMobileOTPModalVisible(false);
            }}
            isMobileOTPModalVisible={isMobileOTPModalVisible}
          />
          <Modal
            width={"90%"}
            maskClosable={false}
            visible={isOfferModal}
            onOk={() => {
              setIsOfferModal(false);
            }}
            onCancel={() => {
              setIsOfferModal(false);
            }}
            footer={null}
            destroyOnClose={true}
          >
            <div></div>
          </Modal>
        </div>
      ) : (
        <div className="container">
          <div className={cx(styles.headerDiv)}>
            <div className={cx(styles.emptyCart)}>
              <h1>Your cart is empty.</h1>
              <p> Explore our products and find something you like. </p>
              <Button type="primary" href="/home">
                Continue Shopping
              </Button>
            </div>
          </div>
        </div>
      )}

      <GiftSheetModal
        isCheckOutModal
        giftSheetExcel={giftSheetExcel}
        giftSheetTitle={prod?.additional?.gift_sheet?.title}
        isGiftModal={isGiftModal}
        setIsGiftModal={setIsGiftModal}
        setGiftSheetExcel={setGiftSheetExcel}
        uploadGiftSheet={uploadGiftSheet}
      />
    </>
  );
};

export default Cart;
