import styles from "pages/menu/components/MenuList/ProductCard.module.css";
import { Card, Button, Badge } from "antd";
import ProText from "components/ProText.tsx";
import ArabicPrice from "components/ArabicPrice";
import { colors } from "ThemeConstants.ts";
import { ItemDescriptionIcons } from "components/ItemDescriptionIcons/ItemDescriptionIcons.tsx";
import { StarOutlined } from "@ant-design/icons";
import ImageWithFallback from "components/ImageWithFallback";
import { Product } from "utils/types/appTypes.ts";
import useBreakPoint from "hooks/useBreakPoint.ts";
import { useAppSelector } from "redux/hooks.ts";
import { useParams, useNavigate } from "react-router-dom";
import { ProductPreviewDialog } from "pages/menu/components/ProductPreviewDialog";
import { useState } from "react";

type Props = {
  item: Product;
};
export default function ProductCard({ item }: Props) {
  const { isRTL } = useAppSelector((state) => state.locale);
  const { themeName } = useAppSelector((state) => state.theme);
  const { isMobile, isTablet, isDesktop } = useBreakPoint();
  const { items } = useAppSelector((state) => state.order);
  const { subdomain } = useParams();
  const navigate = useNavigate();
  // Dialog state
  const [isDialogOpen, setIsDialogOpen] = useState(false);

  // Handle dialog close
  const handleDialogClose = () => {
    setIsDialogOpen(false);
  };

  // Handle product click - open dialog on desktop, navigate on mobile/tablet
  const handleProductClick = (item: Product) => {
    localStorage.setItem("product", JSON.stringify(item));
    if (isDesktop) {
      setIsDialogOpen(true);
    } else {
      navigate(`/${subdomain}/product/${item.id}`);
    }
  };
  return (
    <>
      <div
        key={item.id}
        className={styles.productLink}
        onClick={() => handleProductClick(item)}
      >
        <Card
          key={item.id}
          style={{
            borderRadius: 8,
            overflow: "hide",
            width: "100%",
            boxShadow: "none",
          }}
          styles={{
            body: {
              display: "flex",
              flexDirection: "column",
              justifyContent: "space-between",
              padding: item.description
                ? "16px 16px 8px 16px"
                : "16px 16px 24px 16px",
              overflow: "hide",
              boxShadow: "none",
            },
          }}
        >
          <div
            style={{
              display: "flex",
              alignItems: "center",
              justifyContent: "space-between",
              height: "100%",
              gap: isMobile ? 10 : 16,
            }}
          >
            <div
              style={{
                display: "flex",
                flexDirection: "column",
                justifyContent: "space-between",
                gap: "0.5rem",
              }}
            >
              <ProText
                style={{
                  margin: 0,
                  display: "inline-block",
                  fontSize: "1rem",
                  fontWeight: 600,
                  letterSpacing: "-0.01em",
                  lineHeight: 1.2,
                  color: themeName === "dark" ? "#fff" : "#000044",
                }}
              >
                {isRTL ? item.name : item.nameOther}
              </ProText>
              {item.description && (
                <ProText
                  type="secondary"
                  className={styles.itemDescription}
                  style={{
                    display: "-webkit-box",
                    WebkitBoxOrient: "vertical",
                    WebkitLineClamp: 2,
                    overflow: "hidden",
                    textOverflow: "ellipsis",
                    wordWrap: "break-word",
                    overflowWrap: "break-word",
                    lineHeight: "1.5rem",
                    maxHeight: "3em",
                    fontSize: "1rem",
                    letterSpacing: "0.01em",
                  }}
                >
                  {item.description}
                </ProText>
              )}

              <div>
                {item.original_price !== item.price && (
                  <ArabicPrice
                    price={item.original_price}
                    strong
                    style={{
                      fontSize: "1rem",
                      fontWeight: 700,
                      color: colors.primary,
                      textDecoration: "line-through",
                      marginRight: isRTL ? 0 : 10,
                      marginLeft: isRTL ? 10 : 0,
                    }}
                  />
                )}
                <ArabicPrice
                  price={item.price}
                  strong
                  style={{
                    fontSize: "1rem",
                    fontWeight: 700,
                    color: colors.primary,
                  }}
                />
              </div>

              <div
                style={{
                  position: "relative",
                  ...(isRTL ? { right: -5 } : {}),
                }}
              >
                <ItemDescriptionIcons className={styles.itemDescriptionIcons} />
              </div>
            </div>
            <div style={{ position: "relative" }}>
              {item.isHasLoyalty && (
                <Button
                  className={styles.loyaltyButton}
                  icon={<StarOutlined />}
                  style={{ width: 24, height: 24 }}
                />
              )}
              <Badge
                size="default"
                offset={[-3, 3]}
                count={items
                  .filter((i) => i.id === item.id)
                  .reduce((total, item) => total + item.quantity, 0)}
                color={colors.primary}
                title={`${items
                  .filter((i) => i.id === item.id)
                  .reduce((total, item) => total + item.quantity, 0)} in cart`}
              >
                <ImageWithFallback
                  src={item.image_small || "/default.png"}
                  fallbackSrc="/default.png"
                  alt={item.name}
                  className={`${styles.popularMenuItemImage} ${
                    isMobile
                      ? styles.popularMenuItemImageMobile
                      : isTablet
                        ? styles.popularMenuItemImageTablet
                        : styles.popularMenuItemImageDesktop
                  }`}
                  width={90}
                  height={90}
                />

                {/* <AddToCartButton /> */}
              </Badge>
            </div>
          </div>
        </Card>
      </div>

      {/* Product Preview Dialog for Desktop */}
      {isDialogOpen && (
        <ProductPreviewDialog
          isOpen={isDialogOpen}
          onClose={handleDialogClose}
        />
      )}
    </>
  );
}
