import { RightOutlined, ShoppingCartOutlined } from "@ant-design/icons";
import { Button, Form, Input, message, Row } from "antd";
import {
  addItem,
  selectCart,
  updateSpecialRequest,
} 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 { Product } from "utils/types/appTypes";
import styles from "../product.module.css";

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

  // 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: product?.price,
            image: product?.image,
            description: product?.description,
            variant: variantId,
            extras: selectedExtras,
            extrasgroup: selectedGroups,
            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) => {
    dispatch(updateSpecialRequest(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
              name="specialRequest"
              style={{ position: "relative", top: -5, width: "100%" }}
            >
              <Input
                placeholder={t("cart.specialRequest")}
                size="large"
                autoFocus={false}
                className={styles.inputField}
                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 && (
        <BottomSheet
          isOpen={isSpecialRequestOpen}
          onClose={handleSpecialRequestClose}
          initialValue={specialRequest}
          onSave={handleSpecialRequestSave}
        />
      )}
    </>
  );
}
