// react
import React from "react";
// third-party
import classNames from "classnames";
import { FormattedMessage, useIntl } from "react-intl";
// application
import AppImage from "~/components/shared/AppImage";
import AppLink from "~/components/shared/AppLink";
import AsyncAction from "~/components/shared/AsyncAction";
import CompatibilityStatusBadge from "~/components/shared/CompatibilityStatusBadge";
import url from "~/services/url";
import { IProduct } from "~/interfaces/product";
import { useCartAddItem } from "~/store/cart/cartHooks";
import { Cart20Svg } from "~/svg";
import { useExchangeRate } from "~/services/hooks/useExchangeRate";
import { formatPriceDecimals } from "~/utils/formatPrice";

/** Precio en dólares: usa maximo del producto */
function getDollarPrice(product: IProduct): number {
    // Asegurar que maximo sea un número válido
    if (product.maximo != null && typeof product.maximo === "number" && !isNaN(product.maximo) && product.maximo > 0) {
        return product.maximo;
    }
    // Fallback a price si maximo no está disponible
    const price = typeof product.price === "number" && !isNaN(product.price) ? product.price : 0;
    return price;
}

/** Precio en bolívares: maximo * rate */
function getBolivarPrice(product: IProduct, rate: number): number {
    const dollarPrice = getDollarPrice(product);
    const validRate = typeof rate === "number" && !isNaN(rate) && rate > 0 ? rate : 0;
    return dollarPrice * validRate;
}

export type IProductCardElement = "actions" | "status-badge" | "meta" | "features" | "buttons" | "list-buttons";

export type IProductCardLayout = "grid" | "list" | "table" | "horizontal";

interface Props extends React.HTMLAttributes<HTMLElement> {
    product: IProduct;
    layout?: IProductCardLayout;
    exclude?: IProductCardElement[];
    imageSize?: {
        width?: string;
        height?: string;
    };
    showStatus?: boolean;
}

function ProductCard(props: Props) {
    const { product, layout, exclude = [], className, imageSize = {}, showStatus, ...rootProps } = props;
    const intl = useIntl();
    const featuredAttributes = product.attributes.filter((x) => x.featured);
    const cartAddItem = useCartAddItem();
    const exchangeRate = useExchangeRate();
    const discountValue = Number((product as any).discount ?? 0);
    const hasDiscount = discountValue > 0;

    // Precio en dólares (maximo)
    const dollarPrice = getDollarPrice(product);
    // Precio en bolívares (maximo * rate)
    const bolivarPrice = getBolivarPrice(product, exchangeRate);

    // Precio con descuento aplicado (solo si hasDiscount)
    const discountedDollarPrice = hasDiscount ? dollarPrice * (1 - discountValue / 100) : dollarPrice;
    const discountedBolivarPrice = hasDiscount ? bolivarPrice * (1 - discountValue / 100) : bolivarPrice;

    // Asegurar que ambos sean números válidos antes de usar toFixed
    const dollarPriceFormatted =
        typeof dollarPrice === "number" && !isNaN(dollarPrice) ? formatPriceDecimals(dollarPrice) : "0,00";
    const bolivarPriceFormatted =
        typeof bolivarPrice === "number" && !isNaN(bolivarPrice) ? formatPriceDecimals(bolivarPrice) : "0,00";
    const discountedDollarFormatted =
        typeof discountedDollarPrice === "number" && !isNaN(discountedDollarPrice)
            ? formatPriceDecimals(discountedDollarPrice)
            : "0,00";
    const discountedBolivarFormatted =
        typeof discountedBolivarPrice === "number" && !isNaN(discountedBolivarPrice)
            ? formatPriceDecimals(discountedBolivarPrice)
            : "0,00";

    const rootClasses = classNames("product-card", className, {
        [`product-card--layout--${layout}`]: layout,
    });
    const renderMobileAddQuoteBadge = () => (
        <AsyncAction
            action={() => cartAddItem(product)}
            render={({ run, loading }) => (
                <span
                    className={classNames("badge rounded-pill p-2 badge-discount text-white add-badge", {
                        "product-card__addtocart-full--loading": loading,
                    })}
                    role="button"
                    tabIndex={0}
                    onClick={(event) => {
                        event.preventDefault();
                        event.stopPropagation();
                        run();
                    }}
                    onKeyDown={(event) => {
                        if (event.key === "Enter" || event.key === " ") {
                            event.preventDefault();
                            event.stopPropagation();
                            run();
                        }
                    }}
                >
                                        Cotizar en cotización
                </span>
            )}
        />
    );

    return (
        <div className={rootClasses} {...rootProps}>
            <div className="product-card__image">
                <div className="image image--type--product">
                    <AppLink href={url.product(product)} className="image__body">
                        {product.images && (
                            <AppImage
                                className="image__tag"
                                src={product.images[0]}
                                style={{
                                    objectFit: "contain",
                                    ...imageSize,
                                    borderRadius: "10px",
                                    border: "1px solid #e31e24",
                                }}
                            />
                            
                        )}
                    </AppLink>
                    <span className="text-dark d-sm-none" style={{ fontSize: "12px" }}>CÓDIGO:{product.sku}</span>
                </div>

                {!exclude.includes("status-badge") && (
                    <CompatibilityStatusBadge className="product-card__fit" product={product} />
                )}
            </div>

            <div className="product-card__info">
                {/* {!exclude.includes("meta") && (
                    <div className="product-card__meta">
                        <span className="text-sku" style={{ fontWeight: "bold", color: "#000" }}>CÓDIGO:{product.sku}</span>
                    </div>
                )} */}

                {/* {!exclude.includes("buttons") && product.status === 1 && (
                        <div className=" mt-2">
                            <AsyncAction
                                action={() => cartAddItem(product)}
                                render={({ run, loading }) => (
                                    <button
                                        type="button"
                                        className={classNames("btn btn-primary btn-sm w-100 ", {
                                            "btn-loading": loading,
                                        })}
                                        onClick={run}
                                    >
                                        <FormattedMessage id="BUTTON_ADD_TO_CART" />
                                    </button>
                                )}
                            />
                        </div>
                    )} */}

                <div className="product-card__name product-card-name">
                    <AppLink href={url.product(product)}>{product.name}</AppLink>

                    {showStatus && (
                        <div
                            className="product-status-tag mt-1 mt-lg-4"
                            style={{ display: "flex", gap: "8px", flexWrap: "wrap" }}
                        >
                            <span
                                className={`badge rounded-pill p-2 ${product.status === 1 ? "bg-success" : "bg-secondary"} text-white`}
                            >
                                {product.status === 1 ? "Disponible" : "No disponible"}
                            </span>
                            {/* Badge "En oferta" solo si el descuento es > 0 */}
                            {hasDiscount && (
                                <span className="badge rounded-pill p-2 badge-discount text-white">-{discountValue}% Descuento</span>
                            )}
                            {hasDiscount && (
                                <>
                                    <span className="text-dark d-sm-none d-block" style={{ fontSize: "12px", textDecoration: "line-through" }}>US$ {dollarPriceFormatted}</span>
                                </>
                            )}
                            <span className="text-dark d-sm-none" style={{ fontSize: "16px", fontWeight: "bold" }}>US$ {discountedDollarFormatted}</span>
                            <span className="text-dark d-sm-none" style={{ fontSize: "14px" }}>Bs. {discountedBolivarFormatted}</span>
                        </div>
                    )}

                    {/* {!exclude.includes("buttons") && product.status === 1 && (
                        <div className=" mt-2">
                            <AsyncAction
                                action={() => cartAddItem(product)}
                                render={({ run, loading }) => (
                                    <button
                                        type="button"
                                        className={classNames("btn btn-primary btn-sm w-100 ", {
                                            "btn-loading": loading,
                                        })}
                                        onClick={run}
                                    >
                                        <FormattedMessage id="BUTTON_ADD_TO_CART" />
                                    </button>
                                )}
                            />
                        </div>
                    )} */}

{/* {hasDiscount ? (
                                <>
                                    <div
                                        className="product-card__price product-card__price--old card-price-custom d-lg-block mb-2"
                                        style={{ textDecoration: "line-through", fontSize: "14px", color: "#888" }}
                                    >
                                        US$ {Number(dollarPriceFormatted).toFixed(2)}
                                    </div>
                                    <div className="product-card__price product-card__price--new card-price-custom d-lg-block">
                                        US$ {Number(discountedDollarFormatted).toFixed(2)}
                                    </div>
                                    <div className="product-card__price product-card__price--current card-price-bs d-lg-block">
                                        Bs. {discountedBolivarFormatted}
                                    </div>
                                </>
                            ) : (
                                <>
                                    <div className="product-card__price product-card__price--new card-price-custom d-none d-lg-block">
                                        US$ {dollarPriceFormatted}
                                    </div>
                                    <div className="product-card__price product-card__price--current card-price-bs d-none d-lg-block">
                                        Bs. {bolivarPriceFormatted}
                                    </div>
                                </>
                            )} */}
                </div>

                {!exclude.includes("features") && featuredAttributes.length > 0 && (
                    <div className="product-card__features">
                        <ul>
                            {featuredAttributes.map((attribute, index) => (
                                <li key={index}>
                                    {attribute.name}
                                    {": "}
                                    {attribute.values.map((x) => x.name).join(", ")}
                                </li>
                            ))}
                        </ul>
                    </div>
                )}
            </div>

            <div className="product-card__footer">
                <div
                    className="product-card__prices"
                    style={{
                        display: "flex",
                        flexDirection: "column",
                        alignItems: layout === "list" ? "center" : "start",
                    }}
                >
                    {layout === "list" ? (
                        <>
                            {hasDiscount ? (
                                <>
                                    <div
                                        className="product-card__price product-card__price--old card-price-custom d-none d-lg-block mb-2"
                                        style={{ textDecoration: "line-through", fontSize: "14px", color: "#888" }}
                                    >
                                        US$ {dollarPriceFormatted}
                                    </div>
                                    <div className="product-card__price product-card__price--new card-price-custom d-none d-lg-block">
                                        US$ {discountedDollarFormatted}
                                    </div>
                                    <div className="product-card__price product-card__price--current card-price-bs d-none d-lg-block">
                                        Bs. {discountedBolivarFormatted}
                                    </div>
                                    <div className="product-card__price product-card__price--current card-price-bs d-sm-none">
                                        {renderMobileAddQuoteBadge()}
                                    </div>
                                    
                                </>
                            ) : (
                                <>
                                    <div className="product-card__price product-card__price--new card-price-custom d-none d-lg-block">
                                        US$ {dollarPriceFormatted}
                                    </div>
                                    <div className="product-card__price product-card__price--current card-price-bs d-none d-lg-block">
                                        Bs. {bolivarPriceFormatted}
                                    </div>
                                    <div className="product-card__price product-card__price--current card-price-bs d-sm-none">
                                        {renderMobileAddQuoteBadge()}
                                    </div>
                                </>
                            )}
                        </>
                    ) : (
                        <>
                            {hasDiscount ? (
                                <>
                                    <div
                                        className="product-card__price product-card__price--old pl-3 mt-2 d-none d-lg-block"
                                        style={{ textDecoration: "line-through", fontSize: "14px", color: "#888" }}
                                    >
                                        US$ {dollarPriceFormatted}
                                    </div>
                                    <div className="product-card__price product-card__price--new pl-3 mt-1">
                                        US$ {discountedDollarFormatted}
                                    </div>
                                    <div
                                        className="product-card__price product-card__price--current pl-3 mt-1 mb-3 d-none d-lg-block"
                                        style={{ color: "#888", fontSize: "14px", textDecoration: "line-through" }}
                                    >
                                        Bs. {bolivarPriceFormatted}
                                    </div>
                                    <div
                                        className="product-card__price pl-3 mt-0 mb-3"
                                        style={{ color: "#aaa", fontSize: "16px" }}
                                    >
                                        Bs. {discountedBolivarFormatted}
                                    </div>
                                </>
                            ) : (
                                <>
                                    <div className="product-card__price product-card__price--new pl-3 mt-2">
                                        US$ {dollarPriceFormatted}
                                    </div>
                                    <div
                                        className="product-card__price product-card__price--current pl-3 mt-1 mb-3"
                                        style={{ color: "#aaa", fontSize: "16px" }}
                                    >
                                        Bs. {bolivarPriceFormatted}
                                    </div>
                                </>
                            )}
                        </>
                    )}
                </div>
                {!exclude.includes("buttons") && product.status === 1 && (
                    <React.Fragment>
                        <AsyncAction
                            action={() => cartAddItem(product)}
                            render={({ run, loading }) => (
                                <button
                                    type="button"
                                    className={classNames("product-card__addtocart-icon", {
                                        "product-card__addtocart-icon--loading": loading,
                                    })}
                                    aria-label={intl.formatMessage({ id: "BUTTON_ADD_TO_CART" })}
                                    onClick={run}
                                >
                                    <Cart20Svg />
                                </button>
                            )}
                        />
                        {!exclude.includes("list-buttons") && (
                            <React.Fragment>
                                <AsyncAction
                                    action={() => cartAddItem(product)}
                                    render={({ run, loading }) => (
                                        <button
                                            type="button"
                                            className={classNames(
                                                "product-card__addtocart-full catalog-button d-none d-lg-block",
                                                {
                                                    "product-card__addtocart-full--loading": loading,
                                                },
                                            )}
                                            onClick={run}
                                        >
                                            <FormattedMessage id="BUTTON_ADD_TO_CART" />
                                        </button>
                                    )}
                                />
                            </React.Fragment>
                        )}
                    </React.Fragment>
                )}
            </div>
        </div>
    );
}

export default React.memo(ProductCard);
