import React, { useEffect, useRef, useState } from 'react';
import PropTypes from 'prop-types';
import { createNamespace } from '../../../../../tools/namingTools';
import { THEME_PRIMARY, THEME_SECONDARY } from '../../../../../constants/buttons';
import { CART_URL } from '../../../../../constants/actions';
import { cartShape } from '../../../../../constants/components/prop-types/header';
import { generateUniqueID } from '../../../../../tools/helpers';
import { useDebounceResize } from '../../../../../tools/dimensions/useDebounceResize';
import Icon from '../../../../../atoms/icon/Icon';
import Preloader from '../../../../../atoms/preloader/Preloader';
import ButtonIcon from '../../../../../atoms/button-icon/ButtonIcon';
import CartEditionPreview from '../../../../../atoms/cart-edition-preview/CartEditionPreview';
import CartAddonPreview from '../../../../../atoms/cart-addon-preview/CartAddonPreview';
import { getUrlWithPreviewMode } from '../../../../../tools/urlTools';
import { getBundleDetailsByUuid, normalizeText } from '../../../../../tools/bundleDetails';
// IMPORTANT: (s)css should be imported after other atoms/components
import './styles/HeaderCartOverlay.scss';

const n = createNamespace('HeaderCartOverlay');

const titleId = 'cartOverlayTitle';
const contentId = 'cartOverlayContent';
const renderAddon = ({ itemDetails: addonDetails = {} }) => {
    const { id, branding: { name } } = addonDetails;

    return (
        <div {...n('addon').props} key={generateUniqueID([id, name])}>
            <CartAddonPreview {...addonDetails} variant="cart-overlay" />
        </div>
    );
};

const getBundleProviderFromCartItem = cartItem => normalizeText(
    cartItem?.bundle?.provider?.name
    || cartItem?.bundle?.vendor
);

const getBundleDescriptionFromCartItem = cartItem => normalizeText(
    cartItem?.bundle?.blurb
    || cartItem?.bundle?.description
    || cartItem?.bundle?.overview
);

const getBundleDataFromCartItem = cartItem => {
    const bundleUuid = cartItem?.bundle?.uuid;

    if (!bundleUuid) {
        return null;
    }

    return {
        uuid: bundleUuid,
        name: cartItem?.bundle?.name,
        iconUrl: cartItem?.bundle?.iconUrl,
        provider: getBundleProviderFromCartItem(cartItem),
        description: getBundleDescriptionFromCartItem(cartItem)
    };
};

const groupCartItemsByBundle = cartItems => {
    const sections = [];
    const bundleSectionIndexesByUuid = {};

    cartItems.forEach(cartItem => {
        const bundleData = getBundleDataFromCartItem(cartItem);
        if (!bundleData) {
            sections.push({
                type: 'item',
                item: cartItem
            });
            return;
        }

        const existingSectionIndex = bundleSectionIndexesByUuid[bundleData.uuid];
        if (existingSectionIndex !== undefined) {
            const existingSection = sections[existingSectionIndex];
            existingSection.bundle = {
                ...existingSection.bundle,
                provider: existingSection.bundle?.provider || bundleData.provider,
                description: existingSection.bundle?.description || bundleData.description,
                iconUrl: existingSection.bundle?.iconUrl || bundleData.iconUrl,
                name: existingSection.bundle?.name || bundleData.name
            };
            return;
        }

        bundleSectionIndexesByUuid[bundleData.uuid] = sections.length;
        sections.push({
            type: 'bundle',
            bundle: bundleData
        });
    });

    return sections;
};

const HeaderCartOverlay = ({
    cart,
    isLoggedIn,
    isLoading,
    hasNewProductAdded,
    onClose,
    onMouseLeave,
    onMouseOver,
    onFocus,
    className,
    addToCartError,
    alreadyInCartNotif,
    cartRefCallback,
    baseOrigin,
    partner,
    i18n,
    isBundleGroupingEnabled
}) => {
    const [isScrollEnabled, setScrollState] = useState(false);
    const [cartMaxHeight, setCartMaxHeight] = useState(0);
    const [bundleDetailsByUuid, setBundleDetailsByUuid] = useState({});
    const cartContentRef = useRef();

    const setCartRef = cartRef => {
        cartContentRef.current = cartRef;
        if (cartRefCallback) {
            cartRefCallback(cartRef);
        }
    };

    const setCartHeight = () => {
        if (!cartContentRef.current) {
            return;
        }
        const cartContentNode = cartContentRef.current;
        const cartBounds = cartContentNode.getBoundingClientRect();
        setCartMaxHeight(document.documentElement.clientHeight - cartBounds.top);
        setScrollState(cartBounds.height >= cartMaxHeight);
    };
    useDebounceResize(setCartHeight);
    useEffect(setCartHeight);

    const componentVariables = {
        'cart-overlay-height': cartMaxHeight && `${cartMaxHeight}px`
    };

    const { items: cartItems } = cart || {};
    const bundleUuidsNeedingEnrichment = (isBundleGroupingEnabled && baseOrigin && cartItems?.length)
        ? [...new Set(
            cartItems
                .map(item => item?.bundle?.uuid)
                .filter(Boolean)
        )]
        : [];
    const isBundleEnrichmentLoading = bundleUuidsNeedingEnrichment.some(
        uuid => !bundleDetailsByUuid[uuid]?.enrichmentResolved
    );
    const isCartOverlayLoading = isLoading || isBundleEnrichmentLoading;
    const i18nWithDefaults = { ...HeaderCartOverlay.defaultProps.i18n, ...i18n };
    const { cart: i18nCartBase } = i18nWithDefaults;
    const i18nCart = {
        ...HeaderCartOverlay.defaultProps.i18n.cart,
        ...i18nCartBase
    };
    const hasCartItems = Boolean(cartItems && cartItems.length);
    const isCartActive = isLoggedIn && hasCartItems;

    const showFooter = !isLoggedIn || isCartActive;

    const wrapperModifers = [
        isCartOverlayLoading && 'is-loading'
    ];

    const cartModifiers = [isCartActive && 'active'];
    const contentModifiers = [
        !showFooter && 'no-footer',
        isScrollEnabled && 'with-scrollbar'
    ];

    const viewCartPage = () => {
        window.location.href = getUrlWithPreviewMode(CART_URL);
    };

    const renderCartItem = ({ itemDetails: editionDetails, childItems: addonItems }) => {
        if (!editionDetails) {
            return null;
        }

        const { id, branding: { name } } = editionDetails;

        return (
            <div {...n('product').withTestId().props} key={generateUniqueID([id, name])}>
                <div {...n('edition').withTestId().props}>
                    <CartEditionPreview {...editionDetails} i18n={i18nCart} variant="cart-overlay" />
                </div>
                {Boolean(addonItems && addonItems.length) && (
                    <div {...n('addonList').props}>
                        {addonItems.map(renderAddon)}
                    </div>
                )}
            </div>
        );
    };

    const renderBundleSection = ({ bundle }) => {
        const bundleDetails = bundleDetailsByUuid[bundle?.uuid] || {};
        const shouldWaitForEnrichment = Boolean(isBundleGroupingEnabled && baseOrigin && bundle?.uuid);
        const isBundleResolved = !shouldWaitForEnrichment || Boolean(bundleDetails?.enrichmentResolved);
        const isEnrichmentPending = shouldWaitForEnrichment && !isBundleResolved;
        const bundleName = (bundleDetails?.name || bundle?.name)
            || i18nWithDefaults.bundle
            || i18nCart.bundleLabel;
        let bundleProvider = '';
        let bundleDescription = '';
        let bundleIconUrl = '';

        if (!isEnrichmentPending) {
            // Prefer marketplace enrichment when present; always fall back to cart bundle fields
            // (see getBundleDataFromCartItem) so failed enrichment still shows cart data.
            bundleProvider = bundleDetails?.provider?.name || bundle?.provider || '';
            bundleDescription = bundleDetails?.description || bundle?.description || '';
            bundleIconUrl = bundleDetails?.iconUrl || bundle?.iconUrl || '';
        }

        return (
            <div {...n('bundle').withTestId().props} key={bundle.uuid}>
                {!isEnrichmentPending && (
                    <div {...n('bundleHeader').props}>
                        {bundleIconUrl && (
                            <img
                                {...n('bundleIcon').props}
                                src={bundleIconUrl}
                                alt={bundleName}
                            />
                        )}
                        {!bundleIconUrl && (
                            <div {...n('bundleIconFallback').withTestId().props}>
                                <svg
                                    {...n('bundleIconFallbackSvg').props}
                                    xmlns="http://www.w3.org/2000/svg"
                                    role="img"
                                    aria-label="productGroupsIcon"
                                    height="100%"
                                    width="70%"
                                    viewBox="0 0 32 32"
                                >
                                    <path
                                        d="M4 10v18h22v.75c0 1.794-1.456 3.25-3.25 3.25H3.25C1.456 32 0 30.544 0 28.75V9.25C0 7.456 1.456 6 3.25 6H4v4zm24 12V4H10v18h18zm.75 4H9.25C7.456 26 6 24.544 6 22.75V3.25C6 1.456 7.456 0 9.25 0h19.5C30.544 0 32 1.456 32 3.25v19.5c0 1.794-1.456 3.25-3.25 3.25zm-2.5-15.328c.084.248.013.508-.198.667l-3.613 2.859 1.62 4.351c.131.355.029.73-.272.958-.298.23-.691.241-.997.028l-3.791-2.658-3.791 2.66c-.308.212-.698.202-.997-.028-.299-.228-.403-.604-.272-.958l1.62-4.351-3.613-2.859c-.21-.16-.282-.421-.196-.667s.303-.401.565-.401h4.283l1.841-4.614c.097-.236.308-.379.56-.379s.463.144.558.377l1.841 4.614h4.283c.264 0 .481.157.568.401z"
                                        fill="#474747"
                                    />
                                </svg>
                            </div>
                        )}
                        <div {...n('bundleInfo').props}>
                            <div {...n('bundleTitleRow').props}>
                                <div {...n('bundleName').props}>{bundleName}</div>
                            </div>
                            {bundleProvider && (
                                <div {...n('bundleProvider').withTestId().props}>
                                    {i18nCart.vendor && `${i18nCart.vendor}: `}
                                    <span {...n('bundleProviderValue').withTestId().props}>{bundleProvider}</span>
                                </div>
                            )}
                            {bundleDescription && (
                                <div {...n('bundleDescription').withTestId().props}>{bundleDescription}</div>
                            )}
                            <span {...n('bundleBadge').props}>{i18nCart.bundleLabel}</span>
                        </div>
                    </div>
                )}
            </div>
        );
    };

    useEffect(() => {
        let isMounted = true;
        if (isBundleGroupingEnabled && baseOrigin && cartItems?.length) {
            const bundleUuids = [...new Set(
                cartItems
                    .map(item => item?.bundle?.uuid)
                    .filter(Boolean)
            )];

            if (bundleUuids.length) {
                Promise.all(bundleUuids.map(uuid => (
                    getBundleDetailsByUuid(uuid, partner, baseOrigin)
                        .then(details => ({ uuid, details }))
                )))
                    .then(entries => {
                        if (!isMounted) {
                            return;
                        }
                        setBundleDetailsByUuid(prev => {
                            const next = { ...prev };
                            let hasChanges = false;
                            entries.forEach(({ uuid, details }) => {
                                if (!next[uuid]) {
                                    next[uuid] = details || { enrichmentResolved: true };
                                    hasChanges = true;
                                }
                            });
                            return hasChanges ? next : prev;
                        });
                    })
                    .catch(() => {
                        if (!isMounted) {
                            return;
                        }
                        setBundleDetailsByUuid(prev => {
                            const next = { ...prev };
                            let hasChanges = false;
                            bundleUuids.forEach(uuid => {
                                if (!next[uuid]) {
                                    next[uuid] = { enrichmentResolved: true };
                                    hasChanges = true;
                                }
                            });
                            return hasChanges ? next : prev;
                        });
                    });
            }
        }

        return () => {
            isMounted = false;
        };
    }, [baseOrigin, partner, isBundleGroupingEnabled, cartItems]);

    const renderCloseButton = (
        <ButtonIcon
            {...n('close').props}
            icon="close"
            type="icon"
            hiddenText
            theme={THEME_SECONDARY}
            onClick={onClose}
        >
            {i18nCart.close}
        </ButtonIcon>
    );

    const renderLoading = (
        <div {...n('loading').withTestId().props}>
            <Preloader {...n('preloader').props} isLoading />
            {renderCloseButton}
        </div>
    );

    const renderCartHeader = (
        <div {...n('header').props}>
            <span {...n('title').props} id={titleId}>
                {hasNewProductAdded ? (
                    <>
                        <Icon {...n('titleIcon').props} type="check" />
                        {i18nCart.addedToCart}
                    </>
                ) : i18nCart.cartSummary}
            </span>
            {renderCloseButton}
        </div>
    );

    const renderCartFooter = () => {
        const footerModifiers = [isScrollEnabled && 'with-box-shadow'];
        const buttonProps = {
            ...n('footerButton').props,
            theme: THEME_PRIMARY,
            onClick: viewCartPage
        };

        return (
            <div {...n('footer', footerModifiers).props}>
                {!isLoggedIn && (
                    <ButtonIcon {...buttonProps}>{i18nWithDefaults['sign.in']}</ButtonIcon>
                )}
                {isCartActive && (
                    <ButtonIcon {...buttonProps}>{i18nCart.viewCart}</ButtonIcon>
                )}
            </div>
        );
    };

    const renderedCartItems = (() => {
        if (!isCartActive) {
            return null;
        }

        if (!isBundleGroupingEnabled) {
            return cartItems.map(renderCartItem);
        }

        const groupedCartSections = groupCartItemsByBundle(cartItems || []);
        return groupedCartSections.map(section => {
            if (section.type === 'bundle') {
                return renderBundleSection(section);
            }

            return renderCartItem(section.item);
        });
    })();

    const renderCartContent = (
        <>
            <div {...n('content', contentModifiers).props}>
                <div {...n('cart', cartModifiers).props} id={contentId}>
                    {addToCartError && (
                        <div {...n('message', 'error').withTestId().props}>
                            <Icon type="caution" {...n('messageIcon', 'error').props} />
                            <span {...n('messageText').props}>{i18nCart.addToCartError}</span>
                        </div>
                    )}
                    {!addToCartError && alreadyInCartNotif && (
                        <div {...n('message', 'success').withTestId().props}>
                            <Icon type="check" {...n('messageIcon', 'success').props} />
                            <span {...n('messageText').props}>{i18nCart.alreadyInCart}</span>
                        </div>
                    )}
                    {isCartActive ? renderedCartItems : (
                        <div {...n('cartEmpty').props}>
                            <span {...n('cartTitle').props}>{i18nCart.emptyCart.title}</span>
                            {!isLoggedIn && (
                                <p {...n('cartDescription').props}>{i18nCart.emptyCart['sign.in']}</p>
                            )}
                        </div>
                    )}
                </div>
            </div>
            {showFooter && renderCartFooter()}
        </>
    );

    return (
        <div
            {...n('wrapper', wrapperModifers).withVariables(componentVariables).withClass(className).withTestId().props}
            role="dialog"
            aria-modal="true"
            aria-labelledby={titleId}
            aria-describedby={contentId}
            onMouseLeave={onMouseLeave}
            onMouseOver={onMouseOver}
            onFocus={onFocus}
        >
            <div {...n('mask').props}>
                <div {...n('main', isCartOverlayLoading && 'is-loading').props} ref={setCartRef}>
                    {isCartOverlayLoading ? renderLoading : (
                        <>
                            {renderCartHeader}
                            {renderCartContent}
                        </>
                    )}
                </div>
            </div>
        </div>
    );
};

HeaderCartOverlay.propTypes = {
    cart: PropTypes.shape(cartShape),
    isLoggedIn: PropTypes.bool,
    isLoading: PropTypes.bool,
    hasNewProductAdded: PropTypes.bool,
    className: PropTypes.string,
    i18n: PropTypes.shape({
        'sign.in': PropTypes.string,
        bundle: PropTypes.string,
        cart: PropTypes.shape({
            addedToCart: PropTypes.string,
            cartSummary: PropTypes.string,
            viewCart: PropTypes.string,
            close: PropTypes.string,
            addToCartError: PropTypes.string,
            alreadyInCart: PropTypes.string,
            bundleLabel: PropTypes.string,
            vendor: PropTypes.string,
            productsLabel: PropTypes.string,
            emptyCart: PropTypes.shape({
                title: PropTypes.string,
                'sign.in': PropTypes.string
            })
        })
    }),
    addToCartError: PropTypes.bool,
    alreadyInCartNotif: PropTypes.bool,
    onClose: PropTypes.func,
    onMouseLeave: PropTypes.func,
    onMouseOver: PropTypes.func,
    onFocus: PropTypes.func,
    cartRefCallback: PropTypes.func,
    baseOrigin: PropTypes.string,
    partner: PropTypes.string,
    isBundleGroupingEnabled: PropTypes.bool
};

HeaderCartOverlay.defaultProps = {
    cart: null,
    isLoggedIn: false,
    isLoading: false,
    hasNewProductAdded: false,
    className: null,
    i18n: {
        'sign.in': 'Sign in',
        bundle: 'Bundle',
        cart: {
            addedToCart: 'Added to Cart',
            cartSummary: 'Cart Summary',
            viewCart: 'View Cart',
            close: 'Close the cart summary',
            addToCartError: 'We were unable to add this item to your cart. Please refresh the page and try again.',
            alreadyInCart: 'This item is already in your cart.',
            bundleLabel: 'BUNDLE',
            vendor: 'By',
            productsLabel: 'products',
            emptyCart: {
                title: 'Your cart is empty.',
                'sign.in': 'Sign in to see items you may have added to your cart during a previous visit.'
            }
        }
    },
    addToCartError: false,
    alreadyInCartNotif: false,
    isBundleGroupingEnabled: false,
    baseOrigin: null,
    partner: null,
    cartRefCallback: () => {},
    onClose: () => {},
    onMouseLeave: () => {},
    onMouseOver: () => {},
    onFocus: () => {}
};

export default HeaderCartOverlay;
