import { MinusOutlined, PlusOutlined } from "@ant-design/icons";
import { Button, InputNumber, message } from "antd";
import { useTranslation } from "react-i18next";
import { useNavigate, useParams } from "react-router-dom";
import { useGetRestaurantDetailsQuery } from "redux/api/others";
import styles from "./AddToCartButton.module.css";
import { useAppSelector, useAppDispatch } from "redux/hooks";
import { Product } from "utils/types/appTypes";
import NextIcon from "components/Icons/NextIcon";
import { addItem, removeItem, updateQuantity } from "features/order/orderSlice";
import PlusIcon from "components/Icons/PlusIcon";

export function AddToCartButton({ item }: { item: Product }) {
  const { t } = useTranslation();
  const { isRTL } = useAppSelector((state) => state.locale);
  const { subdomain } = useParams();
  const navigate = useNavigate();
  const dispatch = useAppDispatch();
  const { data: restaurant } = useGetRestaurantDetailsQuery(subdomain, {
    skip: !subdomain,
  });
  const { items } = useAppSelector((state) => state.order);

  // Check if product is in cart
  const cartItemsForProduct = items.filter((i) => i.id === item.id);
  const totalQuantity = cartItemsForProduct.reduce(
    (total, item) => total + item.quantity,
    0,
  );
  const isInCart = totalQuantity > 0;

  // Check if item has extras, variants, or groups
  const hasOptions =
    (item.extras && item.extras.length > 0) ||
    (item.variants && item.variants.length > 0) ||
    (item.theExtrasGroups && item.theExtrasGroups.length > 0);

  // Find basic cart item (no variants/extras) - the one added by quick add
  const basicCartItem = cartItemsForProduct.find(
    (cartItem) =>
      (!cartItem.variant || cartItem.variant === "None") &&
      (!cartItem.extras || cartItem.extras.length === 0) &&
      (!cartItem.extrasgroupnew || cartItem.extrasgroupnew.length === 0),
  );

  const handleClick = (e: React.MouseEvent<HTMLButtonElement>) => {
    e.stopPropagation();
    e.preventDefault();
    if (restaurant && !restaurant.isOpened) {
      message.warning(t("menu.restaurantIsClosed"));
      return;
    }

    // If item has options, navigate to product details page
    if (hasOptions) {
      navigate(`/${subdomain}/product/${item.id}`);
      return;
    }

    // If no options, add item directly to cart
    if (!hasOptions) {
      dispatch(
        addItem({
          item: {
            id: Number(item.id),
            name: item.name,
            price: item.price,
            image: item.image,
            description: item.description,
            variant: "None",
            isHasLoyalty: item.isHasLoyalty,
            no_of_stamps_give: item.no_of_stamps_give,
          },
          quantity: 1,
        }),
      );
    }
  };

  const handleMinusClick = (e: React.MouseEvent<HTMLButtonElement>) => {
    e.stopPropagation();
    e.preventDefault();
    if (restaurant && !restaurant.isOpened) {
      message.warning(t("menu.restaurantIsClosed"));
      return;
    }

    if (basicCartItem && basicCartItem.uniqueId) {
      if (basicCartItem.quantity > 1) {
        // Decrease quantity
        dispatch(
          updateQuantity({
            id: basicCartItem.id,
            uniqueId: basicCartItem.uniqueId,
            quantity: basicCartItem.quantity - 1,
          }),
        );
      } else {
        // Remove item if quantity is 1
        dispatch(removeItem(basicCartItem.uniqueId));
      }
    } else if (cartItemsForProduct.length > 0) {
      // If no basic item found but items exist, remove the first one
      const firstItem = cartItemsForProduct[0];
      if (firstItem.uniqueId) {
        if (firstItem.quantity > 1) {
          dispatch(
            updateQuantity({
              id: firstItem.id,
              uniqueId: firstItem.uniqueId,
              quantity: firstItem.quantity - 1,
            }),
          );
        } else {
          dispatch(removeItem(firstItem.uniqueId));
        }
      }
    }
  };

  const handlePlusClick = (e: React.MouseEvent<HTMLButtonElement>) => {
    e.stopPropagation();
    e.preventDefault();
    if (restaurant && !restaurant.isOpened) {
      message.warning(t("menu.restaurantIsClosed"));
      return;
    }

    if (basicCartItem && basicCartItem.uniqueId) {
      // Increase quantity of existing basic item
      dispatch(
        updateQuantity({
          id: basicCartItem.id,
          uniqueId: basicCartItem.uniqueId,
          quantity: basicCartItem.quantity + 1,
        }),
      );
    } else if (!hasOptions) {
      // Add new basic item if no options
      dispatch(
        addItem({
          item: {
            id: Number(item.id),
            name: item.name,
            price: item.price,
            image: item.image,
            description: item.description,
            variant: "None",
            isHasLoyalty: item.isHasLoyalty,
            no_of_stamps_give: item.no_of_stamps_give,
          },
          quantity: 1,
        }),
      );
    } else {
      // If has options, navigate to product page
      navigate(`/${subdomain}/product/${item.id}`);
    }
  };

  return (
    <div
      className={styles.cartItemActions}
      onClick={(e) => {
        e.stopPropagation();
        e.preventDefault;
      }}
    >
      {isInCart && !hasOptions ? (
        <>
          <div className={styles.quantityControls}>
            <div className={styles.quantityInputContainer}>
              <Button
                shape="circle"
                iconPlacement="start"
                icon={
                  <MinusOutlined title="minus" style={{ color: "black" }} />
                }
                size="small"
                onClick={handleMinusClick}
                className={styles.addButton}
                style={{
                  backgroundColor: "white",
                  width: 28,
                  height: 28,
                  border: "none",
                }}
              />
              <InputNumber
                min={1}
                max={99}
                value={totalQuantity}
                onClick={(e) => {
                  e.stopPropagation();
                  e.preventDefault;
                }}
                onChange={(value: number | null) =>
                  dispatch(
                    updateQuantity({
                      id: item.id,
                      uniqueId: basicCartItem?.uniqueId || "",
                      quantity: value || 1,
                    }),
                  )
                }
                size="small"
                controls={false}
                className={styles.quantityInput}
                name="id"
              />
              <Button
                shape="circle"
                iconPlacement="start"
                icon={<PlusIcon color="#FFF" />}
                size="small"
                onClick={handlePlusClick}
                disabled={totalQuantity >= 99}
                className={styles.addButton}
                style={{
                  backgroundColor: "#FFC600",
                  width: 28,
                  height: 28,
                }}
              />
            </div>
          </div>
        </>
      ) : (
        <Button
          shape="circle"
          iconPlacement="start"
          size="small"
          icon={
            hasOptions ? (
              <NextIcon iconColor="#302E3E" iconSize={16} />
            ) : (
              <PlusOutlined title="add" />
            )
          }
          onClick={handleClick}
          disabled={!hasOptions && totalQuantity >= 99}
          className={styles.addButton}
          style={{
            color: "#302E3E",
            backgroundColor: "white",
            width: 28,
            height: 28,
            position: "absolute",
            [isRTL ? "left" : "right"]: -87,
            bottom: 3,
            minWidth: 28,
            boxShadow:
              "0px 1px 2px 0px #8585851A, 0px 3px 3px 0px #85858517, -1px 7px 4px 0px #8585850D, -1px 13px 5px 0px #85858503, -2px 20px 6px 0px #85858500",
          }}
        />
      )}
    </div>
  );
}
