const ProductDetail = (props) => {
    const { useMemo, useCallback, useState, useEffect } = React;
    const { 
        productInfo, setBaskets, index, config, scrollToFirstPage, 
        member, isMobile = false, fromPage = 'cart', showCart = false, userInfo 
    } = props;

    // 1. Kiểm tra điều kiện dừng sớm (Early Exit)
    if (!productInfo?.product) return null;

    const { product, promotions = [] } = productInfo;
    const [productsSuggest, setProductsSuggest] = useState([]);
    const [loading, setLoading] = useState(false);
    const [quantity, setQuantity] = useState(1);
    const [mainImage, setMainImage] = useState(null);
    const [images, setImages] = useState([]);
 
    const [isCashier, setIsCashier] = useState(0);

    const user_lang = commonFunc.getCookies('user_lang') || 'vi';
    const { Row, Col } = ReactBootstrap;

    // 2. Memoize giá khuyến mãi thấp nhất
    const minPromotionPrice = useMemo(() => {
        if (!promotions) return null;
        const allDiscountedItems = promotions.flatMap(promo => 
            promo.conditions?.items?.filter(item => 
                item.promotion_price < item.normal_price && item.id === product?.item_code
            ) || []
        );
        return allDiscountedItems.length > 0 
            ? Math.min(...allDiscountedItems.map(item => item.promotion_price))
            : null;
    }, [promotions, product?.item_code]);

    // 3. Logic Fetch gợi ý (Tách biệt để dễ quản lý)
    const fetchProductsSuggestByItemCode = useCallback(async (item_code) => {
        if (!config || !item_code ) return;

        try {
            setLoading(true);
            const url = `/api/get-mdc-products-suggest`;
            const dataRequest = {
                barcode: item_code.trim(),
                cust_code: null
            };
           
            const resultObj = await commonApi.APIPOSTByURL(url, dataRequest, config);
            if (resultObj?.status === 200) {
                setProductsSuggest(resultObj.data || []);
            } else {
                setProductsSuggest([]);
            }
        } catch (e) {
            console.error("ERROR get-products-suggest", e);
        } finally {
            setLoading(false);
        }
    }, [config]);

    // 4. Quản lý Ảnh và Suggestion
    useEffect(() => {
        const imagesTmp = product?.images || [];
        
        setImages(imagesTmp);
        setMainImage(imagesTmp.length > 0 ? imagesTmp[0] : null);
        
   
        if (productsSuggest?.length === 0 || 1==1) {
            fetchProductsSuggestByItemCode(product?.item_code);
        }
    }, [product,  fetchProductsSuggestByItemCode, productsSuggest.length]);

    // 5. Cập nhật quyền Cashier
    useEffect(() => {
        setIsCashier(userInfo?.internal_user ? 1 : 0);
    }, [userInfo]);

    // 6. Callback thêm vào giỏ hàng
    const addOneItemToBasket = useCallback((item_code, qty = 1) => {
        const timestamp = Date.now();
        setBaskets(prevBaskets => {
            const currentBaskets = prevBaskets || { items: [], basket: {} };
            const newItems = [...currentBaskets.items];
            const existingItemIndex = newItems.findIndex(item => 
                item.item_code === item_code && (item.line_type || 'S') === 'S'
            );

            if (existingItemIndex !== -1) {
                newItems[existingItemIndex].qty += qty;
            } else {
                newItems.push({ item_code: item_code, qty, line_type: 'S' });
            }

            const newBaskets = {
                ...currentBaskets,
                basket: {
                    ...currentBaskets.basket,
                    basket_id: currentBaskets.basket?.basket_id || timestamp,
                },
                items: newItems,
            };

            commonFunc.setCookies('baskets', JSON.stringify(newBaskets), undefined);
            if (scrollToFirstPage) scrollToFirstPage();
            return newBaskets;
        });
    }, [setBaskets, scrollToFirstPage]);



    // Helper render nội dung HTML
    const renderProductContent = (viField, enField, label) => {
        const content = user_lang === 'vi' ? product?.[viField] : (product?.[enField] || product?.[viField]);
        if (!content) return null;
        return (
            <div className="mb-2">
                <strong>{label}</strong>
                <div className="product-html-content" style={{ fontSize: 14 }} dangerouslySetInnerHTML={{ __html: content }} />
            </div>
        );
    };

    return (
        <div className="product-detail pr-1 pl-1 my-0 bg-white rounded shadow-sm">
            <Row className="mx-0">
                <Col xs={12} md={5} lg={4} className="mb-4 mb-md-0">
                    <ProductImageGallery 
                        images={images} 
                        mainImage={mainImage} 
                        setMainImage={setMainImage}
                        productName={user_lang === 'vi' ? product?.Short_Description_VI : product?.Short_Description_EN}
                        fromPage={fromPage}
                        isMobile={isMobile}
                        showCart={showCart}
                    />
                </Col>

                <Col xs={12} md={7} lg={8}>
                    <ProductPrimaryInfo 
                        product={product} 
                        lang={user_lang} 
                        minPromotionPrice={minPromotionPrice} 
                    />
                    <ProductActions 
                        quantity={quantity} 
                        setQuantity={setQuantity} 
                        onAddToCart={addOneItemToBasket}
                        itemCode={product?.item_code}
                        config = {config}
                    />
                        {/* Khuyến mãi */}
                        {promotions.length > 0 && fromPage === 'cart' && (
                            <div className="mt-2 p-1">
                                <h5 className="fw-bold mb-2">{user_lang === 'vi' ? "Chương Trình Khuyến Mãi" : "Promotions"}</h5>
                                <ul className="list-unstyled">
                                    {promotions.map((promo) => (
                                        <li key={promo?.id} className="mb-3">
                                            <span className="d-block" style={{ color: 'red', fontSize: 14 }}>
                                                <strong>{promo?.code}</strong>: {user_lang === 'vi' ? promo?.name?.vi : promo?.name?.en}
                                                <span className="ms-2" style={{ fontStyle: 'italic', color: 'blue' }}>
                                                    ({user_lang === 'vi' ? "Từ" : "From:"} {commonFunc.formatDate(new Date(promo?.start_date), "YYYY-MM-DD HH:mm").replace('00:00', '')} - {commonFunc.formatDate(new Date(promo?.end_date), "YYYY-MM-DD HH:mm")})
                                                </span>
                                                <span className="ms-2" style={{ color: 'blue', fontStyle: 'italic' }}>
                                                    {promo?.condition_value === '45' ? " (Chỉ dành cho thành viên)" : (promo?.apply_for_branch !== 0 ? `(Chỉ dành cho ${promo?.apply_for_branch})` : "")}
                                                </span>
                                            </span>
                                            <PromotionDisplay divPromoId={`div_promo_display_${promo?.id}_${product?.item_code}`} promotion={promo} item_code={product?.item_code} config={config} />
                                            <PromotionDetail member={member} promo={promo} setBaskets={setBaskets} mainItemCode={product?.item_code} config={config} scrollToFirstPage={scrollToFirstPage} />
                                        </li>
                                    ))}
                                </ul>
                            </div>
                        )}
                </Col>
            </Row>

            {/* Planogram & Thông tin chi tiết */}
            <div className="mt-2" style={{ marginBottom: 5 }}>
                {isCashier === 1 && fromPage === 'cart' && product?.planogram?.length > 0 && (
                    <ContainerExpanse
                        showContentDefault={false}
                        styleHeader={{ padding: '8px 12px', background: '#e9ecef', color: '#495057', borderRadius: '4px' }}
                        HeaderComponent={
                            <h6 className="m-0 fw-bold">
                                <i className="fa fa-sitemap me-2"></i>
                                {user_lang === 'vi' ? "Thông tin Planogram" : "Planogram Information"}
                            </h6>
                        }
                        BodyComponent={<PlanogramList planogram={product.planogram} lang={user_lang} />}
                    />
                )}

                {fromPage === 'cart' && (
                    <ContentContainer maxHeight={150} showContentDefault={isCashier === 0}>
                        <div className="p-2" style={{ fontSize: '14px', lineHeight: '1.5' }}>
                            {renderProductContent('Product_Excerpt_VI', 'Product_Excerpt_EN', user_lang === 'vi' ? "Thông tin sản phẩm:" : "Product information:")}
                            {renderProductContent('Product_Usage_VI', 'Product_Usage_EN', user_lang === 'vi' ? "Hướng dẫn sử dụng:" : "Product instructions:")}
                            {renderProductContent('Product_Additional_Information_VI', 'Product_Additional_Information_EN', user_lang === 'vi' ? "Thông tin bổ sung:" : "Additional information:")}
                            {renderProductContent('Product_Ingredients_VI', 'Product_Ingredients_EN', user_lang === 'vi' ? "Thành phần:" : "Ingredients:")}
                            {renderProductContent('Product_Storage_VI', 'Product_Storage_EN', user_lang === 'vi' ? "Lưu trữ:" : "Storage:")}
                        </div>
                    </ContentContainer>
                )}
            </div>

            {/* Sản phẩm gợi ý */}
            {productsSuggest?.length>0 && (
                <ContainerExpanse
                    showContentDefault={false} 
                    //actionExpand={handleItemSuggestExpand}
                    styleHeader={{ padding: '8px', background: '#616', color: 'white' }}
                    HeaderComponent={
                        <h5 className="m-0 text-center">{config?.lang === 'vi' ? "Sản phẩm gợi ý" : "Product Recommendations"}</h5>
                    }
                    BodyComponent={
                        <div className="p-2">
                            {loading ? <div className="text-center p-3">Loading...</div> : (
                                productsSuggest.map((p, idx) => (
                                    <ProductDetail 
                                        key={p?.item_code || idx} 
                                        productInfo={p} 
                                        setBaskets={setBaskets} 
                                        index={idx + 1} 
                                        scrollToFirstPage={scrollToFirstPage} 
                                        member={member} 
                                        isMobile={isMobile} 
                                        userInfo={userInfo}
                                    />
                                ))
                            )}
                        </div>
                    }
                />
            )}
        </div>
    );
};
