import React, { useEffect, useMemo, useState } from "react";

import ArrowForwardOutlinedIcon from "@mui/icons-material/ArrowForwardOutlined";
import ClearIcon from "@mui/icons-material/Clear";
import ContentWrapper from "../../ContentWrapper/ContentWrapper";

import { Button, TextField } from "@mui/material";

import Header from "../../Header/Header";
import ProductCard from "../components/ProductCard/ProductCard";

import { useDispatch, useSelector } from "react-redux";
import { toast } from "react-toastify";
import {
  getPurchaseDetails,
  removeItemFromCart,
  updatePurchase,
  validateCoupon,
} from "../../redux/purchaseSlice";
import { getFormattedCurrency } from "../../utils";
import style from "./Cart.module.css";

function CartPage() {
  const dispatch = useDispatch();
  // const navigate = useNavigate();

  const { purchaseDetails } = useSelector(({ purchase }) => {
    return {
      purchaseDetails: purchase.purchaseDetails,
    };
  });

  console.log("purchaseDetails", purchaseDetails);

  const removeFromCart = (cartItemId) => {
    if (window.confirm("Do you really want to remove this Item?")) {
      dispatch(removeItemFromCart({ cartItemId }));
    }
  };

  const changeLicenseCount = (cartItemId, licenseCount) => {
    let cartItem = purchaseDetails.cartItems.find(
      ({ _id }) => _id === cartItemId
    );
    cartItem = JSON.parse(JSON.stringify(cartItem));
    if (!cartItem.additionalLicenses || cartItem.additionalLicenses.length <= 0)
      return;
    cartItem.additionalLicenses[0].count = licenseCount;

    dispatch(
      updatePurchase({
        cartItem,
      })
    );
  };

  const changeBuyOnlyLicenseFlag = (cartItemId, value) => {
    let cartItem = purchaseDetails.cartItems.find(
      ({ _id }) => _id === cartItemId
    );

    const payload = {
      _id: cartItem._id,
      planId: cartItem.planId,
      buyingOnlyLicenses: value,
    };

    dispatch(
      updatePurchase({
        cartItem: payload,
      })
    );
  };

  const changeTerm = (cartItemId, newIdx) => {
    let cartItem = purchaseDetails.cartItems.find(
      ({ _id }) => _id === cartItemId
    );
    cartItem = JSON.parse(JSON.stringify(cartItem));

    cartItem.planVariantIdx = newIdx;

    dispatch(
      updatePurchase({
        cartItem,
      })
    );
  };

  const redirectToCheckout = () => {
    // navigate("/purchase/user_details");
    window.location.href = "/purchase/user_details";
  };

  const [couponCode, setCouponCode] = useState("");

  const applyDiscount = () => {
    dispatch(validateCoupon({ couponCode }))
      .unwrap()
      .then((res) => {
        const { getOffer } = res;
        let discount = { code: couponCode };
        if (getOffer.type === "PERCENTAGE")
          discount.percentage = getOffer.amount;
        else if (getOffer.type === "FLAT") discount.amount = getOffer.amount;

        dispatch(
          updatePurchase({
            discount,
          })
        );
        setCouponCode("");
      })
      .catch((err) => {
        toast.error(err.message);
      });
  };

  const removeDiscount = () => {
    dispatch(
      updatePurchase({
        discount: null,
      })
    );
  };

  const isCartEmpty = useMemo(() => {
    return purchaseDetails && purchaseDetails.currency ? false : true;
  }, [purchaseDetails]);

  useEffect(() => {
    dispatch(getPurchaseDetails());
  }, []);

  return (
    <div className={style.main_container}>
      <ContentWrapper>
        <Header theme="DARK2" />
        <div className={style.section1}>
          {" "}
          <p>
            {!isCartEmpty
              ? `Your cart total is ${getFormattedCurrency(
                  purchaseDetails.currency,
                  purchaseDetails.totalCost
                )}`
              : "Your cart is Empty"}
          </p>
          <Button
            variant="contained"
            onClick={redirectToCheckout}
            disabled={isCartEmpty}
          >
            Check Out{" "}
            <ArrowForwardOutlinedIcon
              sx={{ marginLeft: "0.5rem", fontSize: 20 }}
            />
          </Button>
        </div>

        <div className={style.section2}>
          {purchaseDetails &&
            purchaseDetails.cartItems &&
            purchaseDetails.cartItems.map((data) => (
              <ProductCard
                currency={purchaseDetails.currency}
                data={data}
                removeFromCart={removeFromCart}
                changeBuyOnlyLicenseFlag={changeBuyOnlyLicenseFlag}
                changeLicenseCount={changeLicenseCount}
                changeTerm={changeTerm}
              />
            ))}
        </div>

        <div className={style.section3}>
          <div>
            <p>Sub-total</p>
            <p className={style.price}>
              {purchaseDetails
                ? getFormattedCurrency(
                    purchaseDetails.currency,
                    purchaseDetails.subTotalCost
                  )
                : "Nil"}
            </p>
          </div>
          <div>
            <p>Other taxes</p>
            <p className={style.price}>
              {purchaseDetails
                ? getFormattedCurrency(
                    purchaseDetails.currency,
                    purchaseDetails.otherTaxesCost
                  )
                : "Nil"}
            </p>
          </div>
          <div className={style.coupon_row}>
            <p>Have a discount code?</p>
            {purchaseDetails && purchaseDetails.discount ? (
              <>
                <div className={style.coupon_code}>
                  <span>{purchaseDetails.discount.code} </span>{" "}
                  <ClearIcon
                    style={{ cursor: "pointer" }}
                    onClick={removeDiscount}
                  />
                </div>

                <p className={style.price}>
                  {getFormattedCurrency(
                    purchaseDetails.currency,
                    -purchaseDetails.discount.amount
                  )}
                </p>
              </>
            ) : (
              <div className={style.coupon}>
                <TextField
                  fullWidth
                  id="discount_code"
                  placeholder="Discount Code"
                  value={couponCode}
                  onChange={(e) => {
                    setCouponCode(e.target.value);
                  }}
                />
                <Button
                  fullWidth
                  variant="outlined"
                  disabled={!couponCode}
                  onClick={applyDiscount}
                >
                  Apply
                </Button>
              </div>
            )}
          </div>

          <div>
            <p>Total</p>
            <p className={style.price}>
              {purchaseDetails
                ? getFormattedCurrency(
                    purchaseDetails.currency,
                    purchaseDetails.totalCost
                  )
                : "Nil"}
            </p>
          </div>
          <Button
            variant="contained"
            onClick={redirectToCheckout}
            disabled={isCartEmpty}
            className={style.checkout}
          >
            Check Out{" "}
            <ArrowForwardOutlinedIcon
              sx={{ marginLeft: "0.5rem", fontSize: 20 }}
            />
          </Button>
        </div>
      </ContentWrapper>
    </div>
  );
}

export default CartPage;
