import { RightOutlined, ShoppingCartOutlined } from "@ant-design/icons";
import { Button, Form, Input, message, Row } from "antd";
import { addItem } from "features/order/orderSlice";
import useBreakPoint from "hooks/useBreakPoint";
import { BottomSheet } from "pages/cart/components/specialRequest/BottomSheet.tsx";
import { useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { useAppDispatch, useAppSelector } from "redux/hooks";
import { colors, ProBlack2 } from "ThemeConstants";
import { Extra, Product, Variant } from "utils/types/appTypes";
import styles from "../product.module.css";

export default function ProductFooter({
  product,
  isValid = true,
  selectedExtras,
  selectedVariant,
  selectedGroups,
  quantity,
  onClose,
}: {
  product: Product;
  isValid?: boolean;
  selectedExtras: Extra[];
  selectedVariant?: Variant;
  selectedGroups: Record<number, string[]>;
  quantity: number;
  onClose?: () => void;
}) {
  const { t } = useTranslation();
  const dispatch = useAppDispatch();
  const { themeName } = useAppSelector((state) => state.theme);
  const [isSpecialRequestOpen, setIsSpecialRequestOpen] = useState(false);
  const { isMobile, isDesktop } = useBreakPoint();
  const { isRTL } = useAppSelector((state) => state.locale);
  const [specialRequest, setSpecialRequest] = useState("");

  // Check if product has any customization options
  const hasCustomizationOptions = useMemo(() => {
    const hasVariants = product?.variants?.length > 0;
    const hasExtras = product.extras.length > 0;
    const hasExtraGroups = product?.theExtrasGroups?.length > 0;

    return hasVariants || hasExtras || hasExtraGroups;
  }, [
    product?.variants?.length,
    product.extras.length,
    product?.theExtrasGroups?.length,
  ]);

  const handleAddToCart = () => {
    if (!isValid) {
      message.error(t("menu.pleaseSelectRequiredOptions"));
      return;
    }

    if (product) {
      dispatch(
        addItem({
          item: {
            id: product?.id,
            name: product?.name,
            price:
              (selectedVariant?.price || product?.price) +
              selectedExtras.reduce((acc, extra) => acc + extra.price, 0),
            // selectedGroups.reduce((acc, extra) => acc + extra.price, 0),
            image: product?.image,
            description: product?.description,
            comment: specialRequest,
            variant: selectedVariant,
            extras: selectedExtras,
            extrasgroupnew: Object.keys(selectedGroups).map((key) => ({
              groupid: key,
              extrasid: selectedGroups[Number(key)],
            })),
            extrasgroup: [""],
            isHasLoyalty: product?.isHasLoyalty,
            no_of_stamps_give: product?.no_of_stamps_give,
          },
          quantity: quantity,
        }),
      );
      // Navigate back to menu - scroll position will be restored automatically
      if (!isDesktop) window.history.back();
      else {
        onClose?.();
      }
    }
  };

  const handleSpecialRequestSave = (value: string) => {
    setSpecialRequest(value);
  };

  const handleSpecialRequestClose = () => {
    setIsSpecialRequestOpen(false);
  };

  return (
    <>
      <Row
        style={{
          padding: "16px 16px 0",
          ...(!isDesktop
            ? {
                position: "fixed",
                bottom: 0,
                left: 0,
                width: "100%",
                backgroundColor: themeName === "light" ? "white" : ProBlack2,
              }
            : {
                position: "absolute",
                bottom: 0,
                [isRTL ? "right" : "left"]: 0,
                width: hasCustomizationOptions ? "50%" : "100%",
              }),
          height: "135px",
        }}
      >
        <div
          style={{
            width: "100%",
            display: "flex",
            flexDirection: "column",
            gap: "12px",
          }}
        >
          <div
            style={{
              display: "flex",
              gap: "12px",
              width: "100%",
            }}
          >
            <Form.Item style={{ position: "relative", top: -5, width: "100%" }}>
              <Input
                value={specialRequest}
                placeholder={t("cart.specialRequest")}
                size="large"
                autoFocus={false}
                className={styles.inputField}
                onChange={(e) => setSpecialRequest(e.target.value)}
                suffix={
                  <div
                    className={styles.editButton}
                    onClick={() => setIsSpecialRequestOpen(true)}
                  >
                    <u>{t("cart.editNote")}</u> <RightOutlined />
                  </div>
                }
              />
            </Form.Item>
          </div>
          <div
            style={{
              display: "flex",
              gap: "12px",
              width: "100%",
            }}
          >
            <Button
              type="primary"
              icon={<ShoppingCartOutlined />}
              onClick={handleAddToCart}
              disabled={!isValid}
              style={{
                flex: 1,
                height: "48px",
                fontSize: isMobile ? "1rem" : "16px",
                transition: "all 0.3s ease",
                width: "100%",
                borderRadius: 888,
                boxShadow: "none",
                backgroundColor: isValid
                  ? colors.primary
                  : "rgba(233, 233, 233, 1)",
                color: isValid ? "#FFF" : "#999",
                cursor: isValid ? "pointer" : "not-allowed",
              }}
              onMouseEnter={(e) => {
                if (!isMobile && isValid) {
                  e.currentTarget.style.transform = "translateY(-2px)";
                }
              }}
              onMouseLeave={(e) => {
                if (!isMobile) {
                  e.currentTarget.style.transform = "translateY(0)";
                }
              }}
            >
              {isValid ? t("menu.addToCart") : t("menu.selectRequiredOptions")}
            </Button>
          </div>
        </div>
      </Row>

      {!isDesktop && isSpecialRequestOpen && (
        <BottomSheet
          isOpen={isSpecialRequestOpen}
          onClose={handleSpecialRequestClose}
          initialValue={specialRequest}
          onSave={handleSpecialRequestSave}
        />
      )}
    </>
  );
}
