import React, { useEffect, useRef, useState } from 'react';
import PropTypes from 'prop-types';
import { createNamespace } from '../../../tools/namingTools';
import { useRowHeights } from '../../../tools/heights/useRowHeights';
import { useItemsGrid } from '../../../tools/widths/useItemsGrid';
import { getProductEditionsByCartStatus } from '../../../tools/cart';
import { isAppStackable } from '../../../tools/application';
import { cartPreviewStore } from '../../../store/cartPreview';
import { ANCHOR_PRODUCT_EDITIONS, ANCHOR_PRODUCT_ADDONS } from '../../../constants/anchors';
import { CTA_UPGRADE, CTA_ADD_TO_CART } from '../../../constants/actions';
import { parsePricingAction, handleAddToCartAction, handleReplaceEdition, redirectToCart } from '../../../tools/callToActions';
import { getUrlWithPreviewMode, getUrlParams } from '../../../tools/urlTools';
import Grid from '../../grid/Grid';
import SlickSlider from '../../slick-slider/SlickSlider';
import ProductEditionCard from '../card/ProductEditionCard';
import UpgradeModal from '../../../components/upgrade-modal/UpgradeModal';
import DotsNav from '../../dots-nav/DotsNav';
import ReplaceEdition from '../../replace-edition/ReplaceEdition';
// IMPORTANT: (s)css should be imported after other atoms/components
import './styles/ProductEditionList.scss';

const n = createNamespace('ProductEditionList');

const childrenRefNames = ['title'];

const findStackableCartItem = (isStackableWithCartItemIdInUrl, cart, cartItemIdFromUrl, productUuid) => {
    const result = {
        stackableEditionsInCart: {},
        currentCartItemId: null,
        isStackableEditionChange: false
    };

    if (!isStackableWithCartItemIdInUrl || !cart?.items?.length) {
        return result;
    }

    // First try to find by the URL cart item ID
    let cartItem = cart.items.find(item => item.id === cartItemIdFromUrl);

    // If not found (e.g., after replace, the ID changed), find any item for this product
    if (!cartItem && productUuid) {
        cartItem = cart.items.find(item => item?.itemDetails?.uuid === productUuid);
    }

    if (cartItem?.pricingPlanId) {
        result.stackableEditionsInCart[cartItem.pricingPlanId] = cartItem.id;
        result.currentCartItemId = cartItem.id;
        result.isStackableEditionChange = true;
    }

    return result;
};

export const ProductEditionListComponent = ({
    data: {
        editions,
        configurator,
        i18n: i18nProp,
        locale,
        productUuid,
        applicationType,
        user = {},
        crossSellManagementEnabled
    },
    hasAddons,
    selectedEditionId,
    configuratorMode,
    carouselEnabled,
    carouselSlidesToShow,
    hiddenTitle,
    onEditionSelect,
    isIncludedHidden,
    showCode,
    focusWhenTabSelected
}) => {
    const [isEditionsCollapsed, setEditionsCollapsedState] = useState(configuratorMode);
    const sliderRef = useRef(null);
    const [containerRef, gridColumns] = useItemsGrid();
    const [itemRefs, childrenRefs, editionHeights] = useRowHeights(editions.length, childrenRefNames, showCode);
    const [upgradeDetails, setUpgradeDetails] = useState(null);
    const i18n = { ...ProductEditionListComponent.defaultProps.data.i18n, ...i18nProp };

    const { userUuid, companyUuid } = user;
    const { cart, fetchCart, clearCart } = cartPreviewStore();
    const [showReplaceEditionIndex, setShowReplaceEditionIndex] = useState(-1);
    const nonStackableProduct = !isAppStackable(applicationType);

    // Check if cartItemId is in URL params (for stackable edition change flow)
    const urlParams = getUrlParams();
    const cartItemIdFromUrl = urlParams.cartItemId?.[0];
    const isStackableWithCartItemIdInUrl = !nonStackableProduct && cartItemIdFromUrl;

    // fetch once, cart is updated by zustand store (fetch early if we have a cartItemId in URL)
    useEffect(() => {
        if (nonStackableProduct || isStackableWithCartItemIdInUrl) {
            fetchCart(locale);
        }
    }, [fetchCart, nonStackableProduct, isStackableWithCartItemIdInUrl, locale]);

    const {
        editionsInCart,
        editionsReplace
    } = getProductEditionsByCartStatus(editions, cart, productUuid, nonStackableProduct, hasAddons);

    // for non-stackable, there should only be one edition in cart from same product
    const nonStackableEditionInCartItemId = nonStackableProduct && Object.values(editionsInCart)?.[0];

    // For stackable products with cartItemId, filter to only show the specific cart item's edition
    const {
        stackableEditionsInCart,
        currentCartItemId,
        isStackableEditionChange
    } = findStackableCartItem(isStackableWithCartItemIdInUrl, cart, cartItemIdFromUrl, productUuid);

    // hide all ReplaceEdition cards when an item was just added to cart
    useEffect(() => {
        const addToCartFunc = async () => {
            setShowReplaceEditionIndex(-1);

            // For stackable edition change, refetch cart to show updated state
            if (isStackableEditionChange) {
                clearCart();
                await fetchCart(locale);
            }
        };
        document.addEventListener('universalnav:add:cart', addToCartFunc);

        return () => {
            document.removeEventListener('universalnav:add:cart', addToCartFunc);
        };
    }, [isStackableEditionChange, clearCart, fetchCart, locale]);

    const editionInCartItemId = isStackableEditionChange ? currentCartItemId : nonStackableEditionInCartItemId;
    const activeEditionsInCart = isStackableEditionChange ? stackableEditionsInCart : editionsInCart;
    const renderModal = () => {
        const handleClose = () => {
            setUpgradeDetails(null);
        };

        return (
            upgradeDetails && <UpgradeModal upgrades={upgradeDetails} handleClose={handleClose} />
        );
    };

    const renderEdition = (item, index) => {
        const titleRef = childrenRefs.title && childrenRefs.title[index];
        const infoRef = childrenRefs.info && childrenRefs.info[index];
        const mainRef = itemRefs[index];
        const { main, children } = editionHeights;
        const height = main && main[index];
        const titleHeight = children && children.title && children.title[index];
        const infoHeight = children && children.info && children.info[index];

        const eppId = item?.plans?.[0]?.uuid;
        const isReplaceEditionInCart = !crossSellManagementEnabled && editionsReplace?.includes(eppId);
        const isAddedToCart = !!(
            (nonStackableProduct || isStackableEditionChange) && eppId && activeEditionsInCart?.[eppId]
        );

        const replaceEditionInCart = () => {
            if (isReplaceEditionInCart || isStackableEditionChange) {
                handleReplaceEdition(
                    cart?.id,
                    editionInCartItemId,
                    eppId,
                    userUuid,
                    companyUuid,
                    nonStackableProduct,
                    hasAddons
                );
            }
        };

        if (showReplaceEditionIndex === index) {
            return (
                <ReplaceEdition
                    onSelectEdition={replaceEditionInCart}
                    onViewCart={redirectToCart}
                    onExit={() => setShowReplaceEditionIndex(-1)}
                    editionName={item?.name}
                    ref={{ mainRef, titleRef }}
                    i18n={i18n.replaceEdition}
                />
            );
        }

        const onSelect = () => {
            if (isReplaceEditionInCart || isStackableEditionChange) {
                setShowReplaceEditionIndex(index);
            } else {
                onEditionSelect(item, configurator, setUpgradeDetails);
            }
        };

        const onKeyboardSelection = e => {
            if (e.key === ' ' || e.key === 'Enter') {
                e.preventDefault();
                onSelect();
                focusWhenTabSelected?.focus();
            }
        };

        return (
            <ProductEditionCard
                key={item.id}
                data={item}
                i18n={i18n}
                isSelected={(!!selectedEditionId && selectedEditionId === item.id)}
                configuratorMode={configuratorMode}
                isDetailCollapsed={isEditionsCollapsed}
                ref={{ mainRef, infoRef, titleRef }}
                height={height}
                titleHeight={titleHeight}
                carouselEnabled={carouselEnabled}
                infoHeight={infoHeight}
                onSelect={onSelect}
                onExpand={() => setEditionsCollapsedState(!isEditionsCollapsed)}
                isIncludedHidden={isIncludedHidden}
                showCode={showCode}
                isAddedToCart={isAddedToCart}
                nonStackableProduct={nonStackableProduct || isStackableEditionChange}
                hasAddons={hasAddons}
                moveFocusOnKeyboardSelection={onKeyboardSelection}
            />
        );
    };

    const [currentSlide, setCurrentSlide] = useState(0);
    const afterChange = index => {
        // change of state is necessary on each change,
        // to trigger the layout effect that will check for slide's a11y tabindex
        setCurrentSlide(index);
    };

    const headerModifiers = [hiddenTitle && 'no-title', i18n.viewAddons && 'with-link'];
    const titleModifers = [hiddenTitle && 'hidden', i18n.viewAddons && 'with-link'];

    return (
        <section {...n('wrapper').props} id={ANCHOR_PRODUCT_EDITIONS} ref={containerRef}>
            {(i18n.selectEditionTitle || i18n.viewAddons) && (
                <header {...n('header', headerModifiers).props}>
                    {i18n.selectEditionTitle && <h2 {...n('title', titleModifers).props}>{i18n.selectEditionTitle}</h2>}
                    {hasAddons && <a href={`#${ANCHOR_PRODUCT_ADDONS}`} {...n('headerLink').props}>{i18n.viewAddons}</a>}
                </header>
            )}
            <div {...n('content').props}>
                {carouselEnabled ? (
                    <>
                        <SlickSlider
                            settings={{
                                ref: sliderRef,
                                draggable: false,
                                infinite: false,
                                dots: false,
                                slidesToShow: carouselSlidesToShow,
                                afterChange
                            }}
                        >
                            {editions.map(renderEdition)}
                        </SlickSlider>
                        <div {...n('dots').props}>
                            <DotsNav
                                nItems={editions.length}
                                currentIndex={currentSlide}
                                goTo={sliderRef.current && sliderRef.current.slickGoTo}
                            />
                        </div>
                    </>
                ) : (
                    <Grid maxCol={gridColumns}>
                        {editions.map(renderEdition)}
                    </Grid>
                )}
            </div>

            {renderModal()}
        </section>
    );
};

const priceType = PropTypes.shape({
    formattedFullPriceElements: PropTypes.arrayOf(PropTypes.string),
    originalFullPriceElements: PropTypes.arrayOf(PropTypes.string),
    unit: PropTypes.shape({
        limitLabel: PropTypes.string
    })
});

export const defaultEditionsProps = PropTypes.shape({
    editions: PropTypes.arrayOf(
        PropTypes.shape({
            name: PropTypes.string,
            description: PropTypes.string,
            id: PropTypes.number,
            primary: PropTypes.bool,
            plans: PropTypes.arrayOf(
                PropTypes.shape({
                    costs: PropTypes.shape({
                        flatPrice: priceType,
                        unitPrice: PropTypes.arrayOf(priceType)
                    }),
                    uuid: PropTypes.string
                })
            ),
            audience: PropTypes.arrayOf(
                PropTypes.shape({
                    content: PropTypes.string
                })
            ),
            items: PropTypes.arrayOf(
                PropTypes.shape({
                    content: PropTypes.string
                })
            ),
            bullets: PropTypes.arrayOf(
                PropTypes.shape({
                    content: PropTypes.string,
                    tooltip: PropTypes.string
                })
            )
        })
    ),
    locale: PropTypes.string,
    configurator: PropTypes.shape({
        enabled: PropTypes.bool,
        url: PropTypes.string
    }),
    i18n: PropTypes.shape({
        audience: PropTypes.string,
        inclusions: PropTypes.string,
        mostPopular: PropTypes.string,
        selectEditionTitle: PropTypes.string,
        select: PropTypes.string,
        selected: PropTypes.string,
        hideDetails: PropTypes.string,
        viewDetails: PropTypes.string,
        viewAddons: PropTypes.string,
        cart: PropTypes.shape({
            addedToCart: PropTypes.string
        }),
        replaceEdition: PropTypes.object
    }),
    user: PropTypes.object,
    productUuid: PropTypes.string.isRequired,
    applicationType: PropTypes.string.isRequired,
    crossSellManagementEnabled: PropTypes.bool
});

ProductEditionListComponent.propTypes = {
    data: defaultEditionsProps,
    hasAddons: PropTypes.bool,
    selectedEditionId: PropTypes.number,
    configuratorMode: PropTypes.bool,
    carouselEnabled: PropTypes.bool,
    carouselSlidesToShow: PropTypes.number,
    hiddenTitle: PropTypes.bool,
    onEditionSelect: PropTypes.func,
    isIncludedHidden: PropTypes.bool,
    showCode: PropTypes.bool,
    focusWhenTabSelected: PropTypes.object
};

ProductEditionListComponent.defaultProps = {
    data: {
        editions: [],
        configurator: {
            enabled: true,
            url: ''
        },
        locale: 'en-US',
        i18n: {
            audience: 'Ideal For',
            inclusions: 'Included',
            mostPopular: 'Most Popular',
            selectEditionTitle: 'Select an edition for this product',
            hideDetails: 'Hide Details',
            viewDetails: 'View Details',
            viewAddons: 'View Add-ons',
            cart: {
                addedToCart: 'Added to Cart'
            }
        },
        user: {
            isLoggedIn: false
        },
        crossSellManagementEnabled: false
    },
    hasAddons: false,
    carouselEnabled: false,
    carouselSlidesToShow: 1,
    selectedEditionId: 0,
    configuratorMode: false,
    hiddenTitle: false,
    isIncludedHidden: false,
    showCode: false,
    onEditionSelect: (edition, configurator = {}, setUpgradeDetails) => {
        const { id, callToAction = {} } = edition;

        const pricingAction = parsePricingAction(callToAction);
        const paramEdition = `editionId=${id}`;
        const url = configurator.enabled ? `${configurator.url}?${paramEdition}` : pricingAction.url;

        switch (callToAction.actionType) {
            case CTA_UPGRADE:
                setUpgradeDetails(callToAction.popup);
                break;
            case CTA_ADD_TO_CART:
                handleAddToCartAction(edition);
                break;
            default:
                window.location.assign(getUrlWithPreviewMode(url));
        }
    },
    focusWhenTabSelected: null
};

export default ProductEditionListComponent;
