import { Badge, Card, Grid } 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 { useTranslation } from "react-i18next";
import { useNavigate } from "react-router-dom";
import { useAppSelector } from "redux/hooks";
import { colors } from "ThemeConstants";
import { Product } from "utils/types/appTypes";
import { AddToCart } from "../AddToCart";
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 }>;
}

const { useBreakpoint } = Grid;

export function MenuList({ data, categoryRefs }: MenuListProps) {
  const { isRTL } = useAppSelector((state) => state.locale);
  const products = data?.products;
  const { xs, md } = useBreakpoint();
  const { items } = useAppSelector((state) => state.order);
  const restaurantName = localStorage.getItem("restaurantName");
  const navigate = useNavigate();
  const { t } = useTranslation();
  const { themeName } = useAppSelector((state) => state.theme);

  // 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" }}
            >
              <ImageWithFallback
                src={category.image || "/default.png"}
                fallbackSrc="/default.png"
                alt={category.name}
                width="100%"
                height={130}
                style={{
                  width: "100%",
                  objectFit: "cover",
                  borderRadius: 8,
                  overflow: "hidden",
                }}
                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
                style={{
                  display: "flex",
                  flexDirection: "column",
                  gap: "1rem",
                }}
              >
                {categoryProducts.map((item: Product) => (
                  <div
                    key={item.id}
                    className={styles.productLink}
                    onClick={() => {
                      localStorage.setItem("product", JSON.stringify(item));
                      navigate(`/${restaurantName}/product/${item.id}`);
                    }}
                  >
                    <Card
                      key={item.id}
                      style={{
                        borderRadius: 8,
                        overflow: "hide",
                      }}
                      styles={{
                        body: {
                          display: "flex",
                          flexDirection: "column",
                          justifyContent: "space-between",
                          borderRadius: 8,
                          padding: item.description
                            ? "16px 16px 8px 16px"
                            : "16px 16px 24px 16px",
                          overflow: "hide",
                          boxShadow:
                            "0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -2px rgba(0, 0, 0, 0.05)",
                        },
                      }}
                    >
                      <div
                        style={{
                          display: "flex",
                          alignItems: "center",
                          justifyContent: "space-between",
                          height: "100%",
                          gap: xs ? 10 : 16,
                        }}
                      >
                        <div
                          style={{
                            display: "flex",
                            flexDirection: "column",
                            justifyContent: "space-between",
                            gap: "0.5rem",
                          }}
                        >
                          <ProText
                            style={{
                              margin: 0,
                              display: "inline-block",
                              fontSize: xs ? "1rem" : 18,
                              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: xs ? 2 : 4,
                                overflow: "hidden",
                                textOverflow: "ellipsis",
                                wordWrap: "break-word",
                                overflowWrap: "break-word",
                                lineHeight: "1.5rem",
                                maxHeight: xs ? "3em" : "6.6em",
                                fontSize: xs ? "1rem" : 18,
                                letterSpacing: "0.01em",
                              }}
                            >
                              {item.description}
                            </ProText>
                          )}

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

                          <div
                            style={{
                              position: "relative",
                              ...(isRTL ? { right: -5 } : {}),
                            }}
                          >
                            <ItemDescriptionIcons
                              className={styles.itemDescriptionIcons}
                            />
                          </div>
                        </div>
                        <div style={{ position: "relative" }}>
                          <ImageWithFallback
                            src={item.image_small || "/default.png"}
                            fallbackSrc="/default.png"
                            alt={item.name}
                            className={`${styles.popularMenuItemImage} ${
                              xs
                                ? styles.popularMenuItemImageMobile
                                : md
                                ? styles.popularMenuItemImageTablet
                                : styles.popularMenuItemImageDesktop
                            }`}
                            width={90}
                            height={90}
                          />

                          <AddToCart item={item} />

                          {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>
    </>
  );
}
