import mergeToNew from "@insite/client-framework/Common/mergeToNew";
import { ProductContextModel } from "@insite/client-framework/Components/ProductContext";
import { CartLineModel } from "@insite/client-framework/Types/ApiModels";
import Clickable, { ClickablePresentationProps } from "@insite/mobius/Clickable";
import Img, { ImgProps } from "@insite/mobius/Img";
import { LazyImageProps } from "@insite/mobius/LazyImage";
import React, { useState } from "react";
import { css } from "styled-components";

interface OwnProps {
    product: CartLineModel | ProductContextModel;
    onClick?: React.EventHandler<React.MouseEvent>;
    extendedStyles?: ProductImageStyles;
    showSmallImage?: boolean;
}

type Props = OwnProps;

export interface ProductImageStyles {
    linkWrappingImage?: ClickablePresentationProps;
    /**
     * @deprecated Use img instead
     */
    image?: LazyImageProps;
    img?: ImgProps;
}

export const productImageStyles: ProductImageStyles = {
    linkWrappingImage: {
        css: css`
            width: 100%;
        `,
    },
    image: {
        css: css`
            img {
                height: 100%;
            }
        `,
    },
    img: {
        css: css`
            height: auto;
            width: 100%;
        `,
    },
};

const ProductImage = ({ product, onClick, extendedStyles, showSmallImage }: Props) => {
    const [styles] = useState(() => mergeToNew(productImageStyles, extendedStyles));

    let altText = "product" in product ? product.product.imageAltText : product.altText;
    if (!altText || altText === "") {
        altText = "product" in product ? product.product.productTitle : product.productName;
    }

    const imagePath =
        "product" in product
            ? showSmallImage
                ? product.product.smallImagePath || product.product.mediumImagePath
                : product.product.mediumImagePath || product.product.smallImagePath
            : product.smallImagePath;

    const productDetailPath = "product" in product ? product.productInfo.productDetailPath : product.productUri;
    const loading = product.idx === undefined ? "lazy" : product.idx < 3 ? "eager" : "lazy";

    return (
        <Clickable
            {...styles.linkWrappingImage}
            href={productDetailPath}
            onClick={onClick}
            data-test-selector="productImage"
        >
            <Img {...styles.img} loading={loading} width="209" height="209" src={imagePath} altText={altText} />
        </Clickable>
    );
};

export default ProductImage;
