/* eslint-disable @next/next/no-img-element */
"use client";

import { useCart } from "@/app/[name]/(Dialogs)/cart/hook/useCart";
import type { Product, ProductImage } from "@/app/[name]/(Main)/types/Types";
import { formatPurchaseQuantity, getPrimaryVariantId, getProductEffectivePrice, getPurchaseUnitLabel, hasVariants, isVariablePricing } from "@/app/[name]/(Main)/types/Types";
import { CartQuantityControl } from "@/components/CartQuantityControl";
import { ArrowLeft } from "iconsax-react";
import Link from "next/link";
import { useParams } from "next/navigation";
import { memo, useMemo, type ReactNode } from "react";

export type MenuItemViewMode = "list" | "grid";

interface MenuItemProps {
  product: Product;
  /** در صفحه سبد هر خط با variantId مشخص می‌شود */
  variantId?: string | null;
  /** مقدار تنوع (مثلاً «قرمز»، «تنوع سوم») — برای نمایش در سبد خرید */
  variantValue?: string | null;
  /** حالت نمایش: list = یک ستونه (پیش‌فرض)، grid = دو ستونه */
  viewMode?: MenuItemViewMode;
  /** فقط نمایش اطلاعات بدون دکمه‌های افزودن/جزئیات */
  readOnly?: boolean;
  /** تعداد انتخاب‌شده — در حالت readOnly نمایش داده می‌شود */
  displayQuantity?: number;
  /** برچسب اختیاری بالای آیتم */
  badge?: ReactNode;
}

const MenuItem = ({ product, variantId: variantIdProp, variantValue: variantValueProp, viewMode = "list", readOnly = false, displayQuantity, badge }: MenuItemProps) => {
  const { items, addToCart, removeFromCart, isCartMutating } = useCart();
  const params = useParams<{ name: string }>();
  const name = params?.name || "";
  const variantId = variantIdProp ?? getPrimaryVariantId(product);
  const selectedVariant = variantId ? product.variants?.find((v) => v.id === variantId) : undefined;
  const withVariants = hasVariants(product);
  const withVariablePricing = isVariablePricing(product);
  /** در لیست منو اگر تنوع یا قیمت متغیر داشت دکمه جزئیات؛ در سبد همیشه افزودن/کم کردن */
  const showDetailsInsteadOfAdd = (withVariants || withVariablePricing) && variantIdProp == null;

  const quantity = useMemo(() => {
    if (!variantId) return 0;
    const item = items?.[variantId];
    if (item && typeof item === "object" && "quantity" in item) {
      return item.quantity || 0;
    }
    return 0;
  }, [items, variantId]);

  const fallbackImage = "/assets/images/no-image.png";
  const resolvedImage = useMemo(() => {
    if (product.image) return product.image;
    if (Array.isArray(product.images) && product.images.length > 0) {
      const [firstImage] = product.images;
      if (typeof firstImage === "string") return firstImage;
      const imageObj = firstImage as ProductImage;
      return (typeof imageObj === "object" && imageObj?.url) || fallbackImage;
    }
    return fallbackImage;
  }, [product.image, product.images]);

  const productName = useMemo(() => product.name || product.title || "بدون نام", [product.name, product.title]);

  /** فقط در سبد خرید تنوع نمایش داده شود */
  const isInCart = variantIdProp != null;
  const variantValueDisplay = isInCart ? (variantValueProp ?? selectedVariant?.value ?? null) : null;

  const productContent = useMemo(() => {
    const content = product.content;
    if (!content) return "";

    if (Array.isArray(content)) {
      return content.filter((item) => item && typeof item === "string").join("، ");
    }

    return "";
  }, [product.content]);

  const productDescription = useMemo(() => {
    const desc = product.description || product.desc;
    if (!desc || typeof desc !== "string") return "";
    return desc.replace(/,/g, "،");
  }, [product.description, product.desc]);

  const effectivePrice = selectedVariant != null ? selectedVariant.price : getProductEffectivePrice(product);
  const finalPrice = useMemo(() => {
    const discount = product.discount || 0;
    if (discount > 0) {
      return Math.max(0, effectivePrice - discount);
    }
    return effectivePrice;
  }, [effectivePrice, product.discount]);

  const formattedPrice = useMemo(() => (finalPrice ? finalPrice.toLocaleString("fa-IR") : "0"), [finalPrice]);

  const variablePriceLabel = useMemo(() => {
    if (!withVariablePricing) return null;
    const unitLabel = getPurchaseUnitLabel(product.purchaseUnit);
    return `قیمت هر ${unitLabel} T ${formattedPrice}`;
  }, [withVariablePricing, product.purchaseUnit, formattedPrice]);

  const formattedOriginalPrice = useMemo(() => (effectivePrice ? effectivePrice.toLocaleString("fa-IR") : "0"), [effectivePrice]);

  const hasDiscount = useMemo(() => (product.discount || 0) > 0, [product.discount]);

  const quantityLabel = useMemo(() => {
    if (displayQuantity == null) return null;
    if (withVariablePricing) {
      return formatPurchaseQuantity(displayQuantity, product.purchaseUnit);
    }
    return `${displayQuantity.toLocaleString("fa-IR")}×`;
  }, [displayQuantity, withVariablePricing, product.purchaseUnit]);

  const handleAddToCart = () => {
    if (variantId) addToCart(variantId);
  };

  const handleRemoveFromCart = () => {
    if (variantId) removeFromCart(variantId);
  };

  const productDetailUrl = `/${name}/${product.id}?category=${product.category.id}`;
  const actionButtonClass = "bg-background active:drop-shadow-xs rounded-md h-8 inline-flex p-1 justify-center items-center gap-2 relative overflow-hidden";
  const actionButtonLabelClass = "text-sm2 pt-0.5 font-normal text-foreground";

  if (viewMode === "grid") {
    return (
      <div className="flex flex-col w-full h-full">
        <Link href={productDetailUrl} className="cursor-pointer rounded-xl aspect-square overflow-hidden flex items-center justify-center max-h-[100px]">
          <img className="rounded-xl max-w-full max-h-full  object-center" src={resolvedImage} alt={productName} />
        </Link>
        <Link href={productDetailUrl} className="cursor-pointer min-w-0 mt-4 flex items-center justify-between gap-2">
          <div className="text-sm2 font-normal text-black dark:text-white wrap-break-word line-clamp-2 min-w-0">{productName}</div>
          {variantValueDisplay && <span className="bg-primary text-primary-foreground text-[10px] px-1 py-0.5 rounded-md shrink-0">{variantValueDisplay}</span>}
        </Link>
        <div className="flex flex-col gap-2 mt-1">
          <div className="flex flex-col gap-1 min-h-10 justify-center" dir="ltr">
            {variablePriceLabel ? (
              <span className="text-sm text-right">{variablePriceLabel}</span>
            ) : hasDiscount ? (
              <>
                <span className="text-xs text-disabled-text line-through">{formattedOriginalPrice} T</span>
                <span className="text-sm font-medium text-primary dark:text-foreground">{formattedPrice} T</span>
              </>
            ) : (
              <span className="text-sm text-right">{formattedPrice} T</span>
            )}
          </div>
          {showDetailsInsteadOfAdd ? (
            <Link href={productDetailUrl} className={`${actionButtonClass} w-full`}>
              <span className={actionButtonLabelClass}>جزئیات</span>
            </Link>
          ) : (
            <CartQuantityControl quantity={quantity} onAdd={handleAddToCart} onRemove={handleRemoveFromCart} isMutating={isCartMutating} fullWidth />
          )}
        </div>
      </div>
    );
  }

  return (
    <>
      {badge && (
        <div className="absolute top-3 left-3 z-10">
          {badge}
        </div>
      )}
      <div className="flex gap-4 w-full min-h-28 items-stretch">
        <Link href={productDetailUrl} className="cursor-pointer shrink-0 self-center">
          <img className="rounded-xl bg-[#F2F2F9] min-w-28 w-28 aspect-square object-cover" src={resolvedImage} height={112} width={112} alt={productName} />
        </Link>
        <div className="flex-1 flex flex-col justify-between min-w-0">
          <Link href={productDetailUrl} className="cursor-pointer min-w-0">
            <div className="min-w-0">
              <div className="flex items-center justify-between gap-2 min-w-0">
                <div className="text-sm2 font-bold text-black dark:text-white wrap-break-word min-w-0">{productName}</div>
                {variantValueDisplay && <span className="bg-primary text-primary-foreground text-[10px] px-1 py-0.5 rounded-md shrink-0">{variantValueDisplay}</span>}
              </div>
              {(productContent || productDescription) && (
                <div className="text-[#7F7F7F] line-clamp-2 text-xs leading-5 font-normal mt-4 wrap-break-word overflow-hidden">{productContent || productDescription}</div>
              )}
            </div>
          </Link>
          <div className="flex flex-col gap-1 mt-2" dir="ltr">
            {variablePriceLabel ? (
              <span className="text-sm text-right">{variablePriceLabel}</span>
            ) : hasDiscount ? (
              <>
                <span className="text-xs text-disabled-text line-through">{formattedOriginalPrice} T</span>
                <span className="text-sm font-medium text-primary dark:text-foreground">{formattedPrice} T</span>
              </>
            ) : (
              <span className="text-sm text-right">{formattedPrice} T</span>
            )}
          </div>
        </div>
        {readOnly && quantityLabel ? (
          <div className="flex flex-col justify-end shrink-0">
            <span className="text-sm font-semibold text-foreground">{quantityLabel}</span>
          </div>
        ) : !readOnly ? (
          <div className="flex flex-col justify-end shrink-0">
            {showDetailsInsteadOfAdd ? (
              <div className="w-[115px]">
                <Link href={productDetailUrl} className={`${actionButtonClass} w-full`}>
                  <span className={actionButtonLabelClass}>جزئیات</span>
                  <ArrowLeft size={16} className="stroke-foreground" />
                </Link>
              </div>
            ) : (
              <div className="w-[115px]">
                <CartQuantityControl quantity={quantity} onAdd={handleAddToCart} onRemove={handleRemoveFromCart} isMutating={isCartMutating} />
              </div>
            )}
          </div>
        ) : null}
      </div>
    </>
  );
};

export default memo(MenuItem);
