import { ShoppingCartCheckoutOutlined } from "@mui/icons-material";
import { PiShoppingCartLight } from "react-icons/pi";
import style from "./cart.module.css";
import RightDrawer from "@/components/utils/rightDrawer";
import { useEffect, useState } from "react";
import Image from "next/image";
import InputText from "../utils/inputText";
import { useSelector, useDispatch } from "react-redux";
import {
  getCartTotalPrice,
  getCartExactTotalPrice,
  cartStoreActions,
  getCartList,
} from "@/store/cart";
import { accountStoreActions } from "@/store/account";
import { useRouter } from "next/router";
import { checkoutStoreActions } from "@/store/checkout";
import NextImage from "@/other/NextImage";

const Cart = (props) => {
  const router = useRouter();
  const totalPrice = useSelector(getCartTotalPrice);
  const currencyType = useSelector((state) => state.generalStore.currency_type);
  const exactTotalPrice = useSelector(getCartExactTotalPrice);
  const storeData = useSelector(getCartList);
  const accountLogin = useSelector((state) => state.accountStore.loggedIn);
  const [open, setOpen] = useState(false);
  const dispatch = useDispatch();
  const account = useSelector((state) => state.accountStore);
  console.log("storeData", storeData);
  const Footer = () => {
    return (
      storeData &&
      storeData.length > 0 && (
        <div className={style.drawer_footer}>
          {totalPrice > 0 && (
            <div className={style.total}>
              Subtotal:
              <span>
                {" "}
                {totalPrice.toFixed(2)} &nbsp; {currencyType}{" "}
              </span>
              {(Number(exactTotalPrice) - Number(totalPrice)).toFixed(2) >
                0 && (
                <div className={style.saving}>
                  Total Savings:{" "}
                  <span>
                    {(Number(exactTotalPrice) - Number(totalPrice)).toFixed(2)}
                  </span>
                  &nbsp; {currencyType}
                </div>
              )}
            </div>
          )}
          <div className={style.checkout}>
            <div
              className={`primary_btn_no_animation ${style.custom_checkout_btn}`}
              onClick={() => {
                setOpen(false);
                dispatch(checkoutStoreActions.storeCart({ cart: storeData }));
                dispatch(checkoutStoreActions.clearPickup());
                router.push("/checkout");
              }}
            >
              <ShoppingCartCheckoutOutlined /> Checkout
            </div>
            <div className={style.cart_footer_msg}>
              Shipping, taxes, and discount codes calculated at checkout.
            </div>
          </div>
        </div>
      )
    );
  };

  const deleteCart = (index) => {
    dispatch(
      cartStoreActions.deleteCart({
        index: index,
        loggedIn: account.loggedIn,
        userid: account.userid,
      })
    );
  };

  const updateCart = (index, value) => {
    dispatch(cartStoreActions.updateProductQty({ index: index, value: value }));
  };

  useEffect(() => {
    console.log(props.open);
    setOpen(props.open);
  }, [props.open]);

  const onClose = () => {
    setOpen(false);
    if (props.onClose) props.onClose();
  };

  const getPrice = (prices, price_type, quantity) => {
    let price = 0;
    if (price_type === "quantity_wise") {
      for (const item of prices) {
        if (quantity <= item.quantity) {
          price = Number(item.price);
          break;
        }
      }
    } else {
      price = Number(prices);
    }
    return price.toFixed(2);
  };

  return (
    <>
      <RightDrawer
        footer={<Footer />}
        title="Shopping Cart"
        icon={<PiShoppingCartLight />}
        open={open}
        className={style.drawer_custom_class}
        onClose={onClose}
      >
        <div className={style.product}>
          {storeData.map((item, index) => (
            <div
              className={style.product_section}
              key={item.name + "_" + index}
            >
              <div
                onClick={() => {
                  router.push(`/product/${item.id}_${item.name}`);
                  onClose();
                }}
                className={`center_grid cursor_pointer`}
              >
                <div className={style.product_image}>
                  <NextImage src={item.image} alt="" fill />
                </div>
                <div className={style.product_title}>
                  {item.name
                    .replaceAll("<b>", "")
                    .replaceAll("</b>", "")
                    .replaceAll("<i>", "")
                    .replaceAll("</i>", "")
                    .replaceAll("</br>", "")}
                </div>
              </div>
              {getPrice(item.price, item.price_type, item.qty) > 0 &&
                (item.offer ? (
                  <div className={style.product_price}>
                    <span>
                      {currencyType}&nbsp;
                      {(
                        getPrice(item.price, item.price_type, item.qty) *
                          Number(item.qty) -
                        (item.offer / 100) *
                          (getPrice(item.price, item.price_type, item.qty) *
                            Number(item.qty))
                      ).toFixed(2)}
                    </span>
                    <span className={style.real_price}>
                      {currencyType}&nbsp;
                      {(
                        getPrice(item.price, item.price_type, item.qty) *
                        Number(item.qty)
                      ).toFixed(2)}
                    </span>
                  </div>
                ) : (
                  <div className={style.product_price}>
                    {currencyType}&nbsp;
                    {(
                      getPrice(item.price, item.price_type, item.qty) *
                      Number(item.qty)
                    ).toFixed(2)}
                  </div>
                ))}
              <div className={style.options}>
                <div className={style.product_qnty}>
                  Qty
                  <InputText
                    type="number"
                    max={item.exactQty === -1 ? 100000 : item.exactQty}
                    min={1}
                    value={item.qty}
                    customClass={style.inputCustomClass}
                    getValue={(value) => {
                      updateCart(index, value);
                    }}
                  />
                </div>
                <div className={style.product_remove}>
                  <div
                    className={`primary_btn ${style.customBtn}`}
                    onClick={() => deleteCart(index)}
                  >
                    Remove
                  </div>
                </div>
              </div>
              <hr />
            </div>
          ))}
        </div>
      </RightDrawer>
    </>
  );
};

export default Cart;
