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

interface MenuListProps {
  data:
    | {
        products: Product[];
        categories: { id: number; name: string; image?: string }[];
      }
    | undefined;
  id: string;
  categoryRefs: React.RefObject<{ [key: number]: HTMLDivElement | null }>;
}

export function MenuList({ data, categoryRefs }: MenuListProps) {
  const { isRTL } = useAppSelector((state) => state.locale);
  const products = data?.products;
  const { isMobile, isTablet, isDesktop } = useBreakPoint();
  const { items } = useAppSelector((state) => state.order);
  const { id } = useParams();
  const navigate = useNavigate();
  const { t } = useTranslation();
  const { themeName } = useAppSelector((state) => state.theme);

  // Dialog state
  const [isDialogOpen, setIsDialogOpen] = useState(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(`/${id}/product/${item.id}`);
    }
  };

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

  // Show error state if data exists but has no products
  if (data && (!data.products || data.products.length === 0)) {
    return (
      <div
        className={styles.menuSections}
        style={{ padding: "40px", textAlign: "center" }}
      >
        <ProText type="secondary">{t("menu.noMenuItemsAvailable")}</ProText>
      </div>
    );
  }

  // Group products by category
  const productsByCategory = products?.reduce(
    (acc, product) => {
      if (product.categoryId && !acc[product?.categoryId]) {
        acc[product?.categoryId] = [];
      }
      acc[product?.categoryId || 0].push(product);
      return acc;
    },
    {} as Record<number, Product[]>,
  );

  return (
    <>
      <div className={styles.menuSections}>
        {data?.categories?.map((category) => {
          const categoryProducts = productsByCategory?.[category.id] || [];
          if (categoryProducts.length === 0) return null;

          return (
            <div
              key={category.id}
              ref={(el) => {
                if (categoryRefs.current) {
                  categoryRefs.current[category.id] = el;
                }
              }}
              style={{ marginBottom: "1rem" }}
            >
              {!isDesktop && (
                <ImageWithFallback
                  src={category.image || "/default.png"}
                  fallbackSrc="/default.png"
                  alt={category.name}
                  width="100%"
                  height={130}
                  className={styles.categoryMenuItemImage}
                  loadingContainerStyle={{
                    width: "100%",
                  }}
                />
              )}
              <ProTitle
                style={{
                  fontSize: "1.25rem",
                  fontWeight: "bold",
                  marginBottom: "1rem",
                  textAlign: "center",
                  color: themeName === "dark" ? "#fff" : "#000044",
                }}
                level={5}
              >
                {isRTL ? category.name : category.name}
              </ProTitle>
              <div className={styles.menuItemsGrid}>
                {categoryProducts.map((item: Product) => (
                  <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 }}
                            />
                          )}

                          <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 />

                          {items.find((i) => i.id === item.id) && (
                            <Badge
                              count={
                                items.find((i) => i.id === item.id)?.quantity
                              }
                              className={
                                styles.cartBadge +
                                " " +
                                (isRTL
                                  ? styles.cartBadgeRTL
                                  : styles.cartBadgeLTR)
                              }
                              style={{
                                backgroundColor: colors.primary,
                              }}
                              title={`${
                                items.find((i) => i.id === item.id)?.quantity
                              } in cart`}
                            />
                          )}
                        </div>
                      </div>
                    </Card>
                  </div>
                ))}
              </div>
            </div>
          );
        })}
      </div>

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