import CheckoutCart from "../components/CheckoutCart/CheckoutCart";
import MediaQuery from "react-responsive";
import MobileHeader from "../components/home/mobile/mobileHeader/MobileHeader";
import InternalPageHeader from "../components/internalPageHeader/InternalPageHeader";
import MobileFooter from "../components/home/mobile/mobileFooter/MobileFooter";
import shopConetxt from "../context/shopConetxt";
import Footer from "../components/home/footer/Footer";
import * as CartApi from "./api/cart";
import * as commonAPI from "./api/common";
import { useEffect, useState, useContext } from "react";
import { useRouter } from "next/router";
import { Image, notification, Spin } from "antd";
import {
  RightOutlined,
  LeftOutlined,
  LoadingOutlined,
} from "@ant-design/icons";
import _, { isEmpty, get } from "lodash";
import {
  getIncreaseQuantityPayload,
  getDecreaseQuantityPayload,
  getIdForCartUpdate,
} from "../utils/cartUtils/cartUpdateUtils";

import * as AddToWishListApi from "../pages/api/wishList";

const antIcon = <LoadingOutlined style={{ fontSize: 24 }} spin />;
import cx from "classnames";
import * as CategoryAPI from "./api/category";
import Loading from "../components/Loading";
import * as CommonApi from "./api/common";
import { baseUrl } from "../constants/urls";
import * as CheckAPI from "./api/ship";
import Head from "next/head";
import OTPModal from "../components/modal/otpModal/OTPModal";
import SEOHead from "../components/SEOHead";
import { seoDataMap } from "../mockData/seoData";
const seoData = seoDataMap["cart"];

const Cart = () => {
  const {
    wishlist,
    addProductToWishlist,
    setWishlistItems,
    removeProductFromWishlist,
  } = useContext(shopConetxt);
  const { cart, setCartItems } = useContext(shopConetxt);
  const [productInvoice, setProductInvoice] = useState({});
  const [loading, setLoading] = useState(false);
  const [loadingIncreament, setLoadingIncreament] = useState(false);
  const router = useRouter();
  const [loginRes, setLoginRes] = useState<any>({});
  const [category, setCategory] = useState([]);
  const [categoryTree, setCategoryTree] = useState([]);
  const [stateArray, setStateArray] = useState([]);
  const [isOTPModalVisible, setIsOTPModalVisible] = useState(false);
  const [selectedProducts, setSelectedProducts] = useState([]);
  const [state, setState] = useState({
    isRouteChanging: false,
    loadingKey: 0,
  });

  const handleCheckboxChange = (product: any) => {
    setSelectedProducts((prevSelected: any) =>
      prevSelected.includes(product)
        ? prevSelected.filter((item: any) => item !== product)
        : [...prevSelected, product]
    );
  };

  useEffect(() => {
    handleRouteChangeStart();
    CategoryAPI.fetchCategory().then((res) => {
      setCategory(res);
    });
    CategoryAPI.fetchCategoryTree().then((res) => {
      setCategoryTree(res.categories);
    });
    const val: any = localStorage.getItem("loginDetails");
    const details = JSON.parse(val);
    setLoginRes(details);
    const tokenData: any = !_.isEmpty(details) ? details.token : null;
    CartApi.cartFetch(tokenData).then((res) => {
      handleRouteChangeEnd();
      setProductInvoice(res?.data);
      if (cart.length === 0) {
        setCartItems(res.data);
      }
    });
    commonAPI.getRequest(`${baseUrl}/api/indian-states`).then((res) => {
      setStateArray(res?.data);
    });
  }, []);

  const handleRouteChangeStart = () => {
    setState((prevState) => ({
      ...prevState,
      isRouteChanging: true,
      loadingKey: prevState.loadingKey ^ 1,
    }));
  };
  const handleRouteChangeEnd = () => {
    setState((prevState) => ({
      ...prevState,
      isRouteChanging: false,
    }));
  };

  const deleteCartItem = (product: any) => {
    setLoading(true);
    handleRouteChangeStart();
    const prod_id = getIdForCartUpdate(
      get(product, "additional.product_id"),
      cart
    );

    const tokenData: any = !_.isEmpty(loginRes) ? loginRes.token : null;
    const params = {
      token: tokenData,
      item_id: prod_id,
    };
    CartApi.removeCartItem(params).then((res_item) => {
      handleRouteChangeEnd();

      setLoading(false);
      setCartItems(res_item.data);
      setProductInvoice(res_item.data);
    });
  };

  const decreaseQuantity = (prod: any) => {
    setLoading(true);
    setLoadingIncreament(true);
    handleRouteChangeStart();
    const payload = getDecreaseQuantityPayload(
      get(prod, "additional.product_id"),
      cart
    );
    if (!isEmpty(payload)) {
      if (payload.quantity === 0) {
        const tokenData: any = !_.isEmpty(loginRes) ? loginRes.token : null;
        const params = {
          token: tokenData,
          item_id: payload.id,
        };
        CartApi.removeCartItem(params).then((res_item) => {
          setLoading(false);
          setLoadingIncreament(false);
          handleRouteChangeEnd();
          setCartItems(res_item.data);
          setProductInvoice(res_item?.data);
        });
      } else {
        const tokenData: any = !_.isEmpty(loginRes) ? loginRes.token : null;
        const finalPayload = { ...payload, token: tokenData };
        CartApi.updateCart(finalPayload).then((res_item) => {
          handleRouteChangeEnd();
          setLoading(false);
          setLoadingIncreament(false);
          if (res_item?.exception) {
            notification.error({
              message: res_item?.message,
              duration: 0,
            });
          } else {
            notification.success({
              message: res_item?.message,
              duration: 1,
            });
          }

          setLoading(false);

          if (res_item.data && res_item.data !== null) {
            setCartItems(res_item.data);
            setProductInvoice(res_item?.data);
          }
        });
      }
    }
  };

  const increaseQuantity = (prod: any) => {
    setLoading(true);
    setLoadingIncreament(true);
    handleRouteChangeStart();
    const payload = getIncreaseQuantityPayload(
      get(prod, "additional.product_id"),
      cart
    );
    console.log(payload, "payload");
    if (!isEmpty(payload)) {
      const tokenData: any = !_.isEmpty(loginRes) ? loginRes.token : null;
      const finalPayload = { ...payload, token: tokenData };
      CartApi.updateCart(finalPayload).then((res_item) => {
        // console.log(res_item,"res_item");
        setLoadingIncreament(false);
        setLoading(false);
        handleRouteChangeEnd();
        if (res_item?.exception) {
          notification.error({
            message: res_item?.message,
            duration: 0,
          });
        } else {
          if (res_item?.status == false) {
            notification.error({
              message: res_item?.message,
              duration: 1,
            });
          } else {
            notification.success({
              message: res_item?.message,
              duration: 1,
            });
          }
        }
        if (res_item.data && res_item.data !== null) {
          setCartItems(res_item.data);
          setProductInvoice(res_item?.data);
        }
      });
    }
  };

  const updateQuantity = (e: any, prod: any) => {
    setLoading(true);

    setLoadingIncreament(true);
    handleRouteChangeStart();
    const payload = {
      id: prod.id,
      quantity: parseInt(e.target.value),
    };

    if (!isEmpty(payload)) {
      const tokenData: any = !_.isEmpty(loginRes) ? loginRes.token : null;
      const finalPayload = { ...payload, token: tokenData };
      CartApi.updateCart(finalPayload).then((res_item) => {
        // console.log(res_item,"res_item");
        setLoadingIncreament(false);
        setLoading(false);
        handleRouteChangeEnd();
        if (res_item?.exception) {
          notification.error({
            message: res_item?.message,
            duration: 0,
          });
        } else {
          if (res_item?.status == false) {
            notification.error({
              message: res_item?.message,
              duration: 1,
            });
          } else {
            notification.success({
              message: res_item?.message,
              duration: 1,
            });
          }
        }
        if (res_item.data && res_item.data !== null) {
          setCartItems(res_item.data);
          setProductInvoice(res_item?.data);
        }
      });
    }
  };

  const changeDeliveryType = (e: any, item: any) => {
    setLoadingIncreament(true);
    handleRouteChangeStart();
    if (e.target.value == 1) {
      CommonApi.getRequest(
        `${baseUrl}/api/dunzo/availability?pickup_lat=${item?.additional?.seller_lat}&pickup_lng=${item?.additional?.seller_lang}&drop_lat=${item?.additional?.customer_lat}&drop_lng=${item?.additional?.customer_lang}`
      ).then((available) => {
        if (available?.status) {
          const tokenData: any = !_.isEmpty(loginRes) ? loginRes.token : null;

          const params = {
            id: item.id,
            type: e.target.value,
            token: tokenData,
          };
          CartApi.deliveryTypeChange(params).then((res) => {
            if (res?.status) {
              CartApi.cartFetch(tokenData).then((res) => {
                setLoadingIncreament(false);
                handleRouteChangeEnd();
                setCartItems(res.data);
                setProductInvoice(res.data);
              });
            } else {
              setLoadingIncreament(false);
              handleRouteChangeEnd();
              notification.error({ message: res?.message });
            }
          });
        } else {
          setLoadingIncreament(false);
          handleRouteChangeEnd();
          notification.error({ message: "Delivery Not Available " });
        }
      });
    } else if (e.target.value == 0) {
      CheckAPI.shippingAvailableCheckingAPI(
        loginRes?.token,
        item?.additional?.seller_pincode,
        item?.additional?.customer_pincode,
        item?.additional?.item_weight
      ).then((res) => {
        if (res?.status) {
          const tokenData: any = !_.isEmpty(loginRes) ? loginRes.token : null;

          const params = {
            id: item.id,
            type: e.target.value,
            token: tokenData,
          };
          CartApi.deliveryTypeChange(params).then((res) => {
            CartApi.cartFetch(tokenData).then((res) => {
              setLoadingIncreament(false);
              handleRouteChangeEnd();
              setCartItems(res.data);
              setProductInvoice(res.data);
            });
          });
        } else {
          handleRouteChangeEnd();
          setLoadingIncreament(false);
          notification.error({ message: "Delivery Not Available " });
        }
      });
    } else {
      const tokenData: any = !_.isEmpty(loginRes) ? loginRes.token : null;

      const params = {
        id: item.id,
        type: e.target.value,
        token: tokenData,
      };
      CartApi.deliveryTypeChange(params).then((res) => {
        CartApi.cartFetch(tokenData).then((res) => {
          handleRouteChangeEnd();
          setLoadingIncreament(false);
          setCartItems(res.data);
          setProductInvoice(res.data);
        });
      });
    }
  };

  const emptyCart = () => {
    handleRouteChangeStart();
    const tokenData: any = !_.isEmpty(loginRes) ? loginRes.token : null;
    const params = {
      token: tokenData,
    };
    CartApi.emptyCartItem(params).then((res) => {
      handleRouteChangeEnd();

      setLoading(false);
      setCartItems({});
      setProductInvoice({});
      // console.log(res, "res")
    });
  };

  const deleteSelectCartItem = () => {
    setLoading(true);


    handleRouteChangeStart();
    const ids = selectedProducts.map((product: any) => product.id);
    
    const tokenData: any = !_.isEmpty(loginRes) ? loginRes.token : null;

    const param = {
      token: tokenData,
      items: ids,
    };
    CartApi.deleteCartItems(param).then((res: any) => {
      if(res?.status){
      notification.success({message:res.message});
      CartApi.cartFetch(tokenData).then((res) => {
        handleRouteChangeEnd();
        setCartItems(res.data);
        setProductInvoice(res.data);
      });
      handleRouteChangeEnd();
    }else{
      notification.error({message:res.message});
      handleRouteChangeEnd();
    }
 
    });
  };

  const moveWishList = (productDetails: any) => {
    if (_.isEmpty(loginRes)) {
      setIsOTPModalVisible(!isOTPModalVisible);
    } else {
      const params = {
        product_id: productDetails?.product?.id,
        token: loginRes?.token,
      };
      AddToWishListApi.addToWishList(params).then((res: any) => {
        if (res.data) {
          addProductToWishlist(res.data);
          deleteCartItem(productDetails);
        }
        notification.success({ message: res.message });
      });
    }
  };

  const img = (
    <Image
      src={"/images/loaderindispare.gif"}
      width={"100%"}
      style={{ background: "#fff", width: "200px", height: "100px" }}
    />
  );

  return (
    <div className="pb-20">
      <Loading isRouteChanging={state.isRouteChanging} key={state.loadingKey} />
      <SEOHead {...seoData} />

      <MediaQuery maxWidth={768}>
        <MobileHeader stateArray={stateArray} />
      </MediaQuery>
      <MediaQuery minWidth={769}>
        <InternalPageHeader
          page={"cart"}
          catagories={category}
          categoryTree={categoryTree}
          stateArray={stateArray}
        />
      </MediaQuery>
      {/* hero component */}
      <div className="del-info-content">
        <CheckoutCart
          products={cart}
          moveWishList={moveWishList}
          productInvoice={productInvoice}
          deleteCartItem={deleteCartItem}
          increaseQuantity={increaseQuantity}
          decreaseQuantity={decreaseQuantity}
          changeDeliveryType={changeDeliveryType}
          setLoadingIncreament={setLoadingIncreament}
          loadingIncreament={loadingIncreament}
          stateArray={stateArray}
          updateQuantity={updateQuantity}
          selectedProducts={selectedProducts}
          emptyCart={emptyCart}
          handleCheckboxChange={handleCheckboxChange}
          deleteSelectCartItem={deleteSelectCartItem}
        />
      </div>
      <MediaQuery maxWidth={768}>
        <MobileFooter stateArray={stateArray} />
      </MediaQuery>
      <MediaQuery minWidth={769}>
        <Footer stateArray={stateArray} />
      </MediaQuery>
      <OTPModal
        page={"home"}
        handleOTPClose={() => {
          setIsOTPModalVisible(false);
        }}
        isOTPModalVisible={isOTPModalVisible}
        stateArray={stateArray}
      />

      {/* <div
        className={cx("justify-center align-center")}
        style={{
          width: "100%",
          left: "50%",
          top: "50%",
          background: "tranparent",
          position: "fixed",
          transform: "translate(-25% , -50%)",
        }}
      >
        <Spin
          spinning={loading}
          indicator={img}
          size="large"
          tip="Loading..."
        />
      </div> */}
    </div>
  );
};

export default Cart;
