"use client";

import { Drawer, IconButton, Typography } from "@material-tailwind/react";
import { usePathname } from "next/navigation";
import { useCallback, useEffect, useRef, useState } from "react";
import { IoIosClose } from "react-icons/io";

import {
  CART_STATUS,
  DEFAULT_CURRENCY,
  QUANTITY_ACTIONS,
} from "../constants/app";
import { FeatureCodes } from "../constants/feature-flags";
import { ROUTES } from "../constants/routes";
import { useMainContext } from "../contexts/MainWrapperContext";
import { useCart } from "../hooks/useCart";
import useCustomRouter from "../hooks/useCustomRouter";
import { useGlobalDebounce } from "../hooks/useDebounce";
import { _useScopedI18n } from "../i18n/client";
import { CartTableItemComponentProps, ICart } from "../types/cart";
import { replaceForbiddenKeyword } from "../utils/app.util";
import ButtonCustom from "./Button";
import CustomNextImage from "./CustomNextImage";
import EmptyCartMessageComponent from "./EmptyCartMessageComponent";
import InputCartQuantity from "./InputCartQuantity";
import ProductPriceComponent from "./ProductPriceComponent";

export type CartDrawerComponentProps = {
  open: boolean;
  closeDrawer: () => void;
  isCartLoading: boolean;
  cartData: ICart;
};

export default function CartDrawerComponent({
  open,
  closeDrawer,
  isCartLoading,
  cartData,
}: CartDrawerComponentProps) {
  //
  const scopeT = _useScopedI18n("sharedComponents.cartDrawerComponent");
  const { featureFlags } = useMainContext();
  const isMembershipFeatureEnabled =
    featureFlags?.[FeatureCodes.ENABLE_MEMBERSHIP_FEATURE]?.isActive;

  const pathname = usePathname();
  const { addToCart, removeProductFromCart, updateCartState } = useCart();
  const { push } = useCustomRouter();
  const lastProcessedQuantityRef = useRef<Map<number, number>>(new Map());
  const [hasError, setHasError] = useState<boolean>(false);
  // Sync last processed quantities with cart data when it updates
  useEffect(() => {
    if (cartData?.cartProducts) {
      cartData.cartProducts.forEach((product) => {
        // Update ref to match current cart quantity (from API response)
        lastProcessedQuantityRef.current.set(product.id, product.quantity);
      });
    }
  }, [cartData]);

  const handleQuantity = useCallback(
    (id: number, qty: number, action: string) => {
      if (cartData) {
        let newCartProducts = [...cartData.cartProducts];
        const targetProduct: CartTableItemComponentProps = newCartProducts.find(
          (item) => item.id === id,
        );
        if (action === QUANTITY_ACTIONS.add) {
          addToCart.mutate({
            productSKU: targetProduct.product.sku,
            quantity: qty,
          });
        } else if (action === QUANTITY_ACTIONS.minus) {
          removeProductFromCart.mutate({
            productSKU: targetProduct.product.sku,
            quantity: qty,
          });
        }
      }
    },
    [cartData, addToCart, removeProductFromCart],
  );

  //todo: create cartProduct interface
  const renderCartDrawerItems = (
    cartProducts: CartTableItemComponentProps[],
  ) => {
    if (!cartProducts || cartProducts?.length === 0)
      return (
        <>
          {" "}
          <EmptyCartMessageComponent />{" "}
        </>
      );
    return (
      <ul className="flex flex-col">
        {" "}
        {cartProducts?.map((cartProduct: CartTableItemComponentProps) =>
          renderCartItem(cartProduct),
        )}
      </ul>
    );
  };

  const handleQuantityChange = useGlobalDebounce(
    (qty: number, cartProduct: CartTableItemComponentProps) => {
      const lastProcessedQty =
        lastProcessedQuantityRef.current.get(cartProduct.id) ??
        cartProduct.quantity;

      if (lastProcessedQty < qty) {
        const diff = qty - lastProcessedQty;
        lastProcessedQuantityRef.current.set(cartProduct.id, qty);
        handleQuantity(cartProduct.id, diff, QUANTITY_ACTIONS.add);
      } else if (lastProcessedQty > qty) {
        const diff = lastProcessedQty - qty;
        lastProcessedQuantityRef.current.set(cartProduct.id, qty);
        handleQuantity(cartProduct.id, diff, QUANTITY_ACTIONS.minus);
      }
    },
    500,
  );

  const renderCartItem = (cartProduct: CartTableItemComponentProps) => {
    const handleQuantityAddingRemoving = (qty: number) => {
      handleQuantityChange(qty, cartProduct);
    };

    return (
      <li
        key={cartProduct.id}
        className="border-b border-b-slate-50 py-3 md:py-4 first-of-type:pt-0"
      >
        <div className="flex gap-2 justify-between items-center ">
          <div className="flex w-3/4 items-center gap-3">
            <div className="w-[60px] border border-slate-50 rounded-md">
              <CustomNextImage
                src={cartProduct.product.featureImage}
                alt={cartProduct.product.name}
                height={60}
                width={60}
              />
            </div>
            <div className="flex justify-start flex-col flex-1 h-full py-1">
              <Typography
                variant="h5"
                className="text-sm font-medium text-black-500 line-clamp-2 font-box"
              >
                {cartProduct.product.name}
              </Typography>
              <Typography
                variant="lead"
                className="text-xs font-medium my-0.5 text-slate-400"
              >
                {scopeT("category")}:{" "}
                {replaceForbiddenKeyword(cartProduct.product.category.name)}
              </Typography>
              {isMembershipFeatureEnabled && cartProduct.isAutoAdded && (
                <Typography
                  variant="small"
                  className="text-xs font-medium text-orange-500"
                >
                  Required for purchase
                </Typography>
              )}

              {cartProduct?.maximumUserCanPurchase &&
                cartProduct.userPurchaseLimit != null &&
                cartProduct.quantity >= cartProduct.maximumUserCanPurchase && (
                  <Typography
                    variant="lead"
                    className="text-xs leading-3 font-medium text-orange-500"
                  >
                    {!!cartProduct.totalOrderExistsForProduct && (
                      <>
                        {scopeT("alreadyPurchased")}
                        &nbsp;
                        {cartProduct.totalOrderExistsForProduct}
                      </>
                    )}
                    {scopeT("maxPurchaseLimit")} {cartProduct.userPurchaseLimit}
                  </Typography>
                )}
            </div>
          </div>
        </div>

        {cartProduct.feedBackMessage && (
          <div className="col-span-12 m-2">
            <Typography
              variant="lead"
              className="text-xs text-center leading-5 font-medium text-orange-500 bg-orange-50 border border-orange-300 p-2 rounded-lg"
            >
              {cartProduct.feedBackMessage}
            </Typography>
          </div>
        )}
        {cartProduct.product.maxCartQuantity !== null && (
          <div className="col-span-12 m-2">
            <Typography
              variant="lead"
              className="text-xs text-center leading-5 font-medium text-orange-500 bg-orange-50 border border-orange-300 p-2 rounded-lg"
            >
              You are allowed to purchase {cartProduct.product.maxCartQuantity}{" "}
              items
            </Typography>
          </div>
        )}
        <div className=" pt-3">
          <div className="flex justify-between items-center flex-wrap">
            <div className=" ml-[20%] border-none  flex items-center justify-end md:justify-start ">
              <div>
                <div className="flex gap-2 items-baseline">
                  <Typography
                    variant="h5"
                    className="text-base font-semibold text-black-500 mb-0 "
                  >
                    <ProductPriceComponent
                      amount={cartProduct?.unitPrice || 0}
                    />
                  </Typography>
                  {cartProduct?.unitDiscount > 0 && (
                    <Typography
                      variant="small"
                      className="text-xs font-semibold line-through text-black-200 mb-0 "
                    >
                      <ProductPriceComponent
                        amount={cartProduct?.unitOriginalPrice || 0}
                      />
                    </Typography>
                  )}
                </div>

                {cartProduct?.unitDiscount > 0 && (
                  <Typography
                    variant="small"
                    className="text-xs font-semibold text-green-500 mb-0 "
                  >
                    Save{" "}
                    <ProductPriceComponent
                      amount={cartProduct?.unitDiscount || 0}
                    />
                  </Typography>
                )}
              </div>
            </div>

            <InputCartQuantity
              quantity={cartProduct.quantity}
              maxCartQuantity={cartProduct.product.maxCartQuantity}
              isLoading={isCartLoading || pathname === ROUTES.dashboard.cart}
              onQuantityChange={handleQuantityAddingRemoving}
              canProductBeRemoved={cartProduct.canProductBeRemoved}
              size="lg"
              maximumUserCanPurchase={
                !!cartProduct.maximumUserCanPurchase
                  ? cartProduct.maximumUserCanPurchase
                  : Infinity
              }
              quantityStepper={cartProduct.product.quantityStepper}
              onErrorChange={(hasErrorFromQuantityInput) =>
                setHasError(hasErrorFromQuantityInput)
              }
            />
          </div>
        </div>
      </li>
    );
  };
  return (
    <>
      <Drawer
        placement="right"
        open={open}
        size={410}
        onClose={closeDrawer}
        className="max-w-[25rem] h-svh"
      >
        <div className="p-3 md:p-3.5 flex items-center justify-between border-b border-b-slate-50 mb-2">
          <Typography
            variant="h5"
            className="text-sm md:text-base font-semibold text-black-500"
          >
            {scopeT("title")}
          </Typography>
          <IconButton
            variant="text"
            className="text-black-500 w-5 h-5"
            onClick={closeDrawer}
          >
            <IoIosClose className="w-6 h-6 text-black-500" />
          </IconButton>
        </div>

        <div className="px-3 md:px-4 mr-1 cartAutoHeight">
          {cartData && renderCartDrawerItems(cartData.cartProducts)}
        </div>

        <ul className="p-3 md:p-4 flex flex-col gap-3">
          <li className="flex justify-between items-center gap-5">
            <Typography
              variant="h5"
              className="text-base font-semibold text-black-500"
            >
              {scopeT("subTotal")}
            </Typography>
            <Typography
              variant="h5"
              className="text-base font-semibold text-black-500"
            >
              {DEFAULT_CURRENCY}
              {cartData && cartData.subTotal}
            </Typography>
          </li>
          <li>
            <ButtonCustom
              onClick={async () => {
                await updateCartState.mutateAsync(CART_STATUS.checkout);
                closeDrawer();
                push(ROUTES.dashboard.checkout);
              }}
              className="w-full"
              icon={undefined}
              loading={updateCartState.isPending}
              disabled={
                (cartData && cartData.cartProducts.length <= 0) || hasError
              }
            >
              {scopeT("checkoutNowBtn")}
            </ButtonCustom>
          </li>
        </ul>
      </Drawer>
    </>
  );
}
