import React, { useState } from 'react';
import PropTypes from 'prop-types';
import { createNamespace } from '../../tools/namingTools';
import { useResponsive } from '../../tools/widths/useResponsive';
import VolumePricing from '../volume-pricing/VolumePricing';
import Icon from '../icon/Icon';
// IMPORTANT: (s)css should be imported after other atoms/components
import './styles/VolumePricingCard.scss';

const n = createNamespace('VolumePricingCard');

const pricingPlans = (pricing = []) => {
    const pricingDataMap = {};
    pricing.forEach(plan => {
        plan.externalSourcePrices.forEach(price => {
            const priceLevelExists = pricingDataMap[price.priceLevel];
            const pricingData = {
                id: plan.id,
                pricingDuration: plan.pricingDuration,
                contract: plan.contract,
                price
            };

            if (priceLevelExists) {
                pricingDataMap[price.priceLevel] = [...priceLevelExists, pricingData];
            } else {
                pricingDataMap[price.priceLevel] = [pricingData];
            }
        });
    });
    return pricingDataMap;
};

const getNumericLevel = level => {
    const parsedLevel = `${level || ''}`.trim();
    return /^\d+$/.test(parsedLevel) ? Number(parsedLevel) : null;
};

const volumePricingLevel = (pricingMap, data) => {
    const temp = [];
    const sortedLevels = Object.entries(pricingMap)
        .map(([key, range], index) => ({ key, range, index }))
        .sort((currentLevel, nextLevel) => {
            const currentNumericLevel = getNumericLevel(currentLevel.key);
            const nextNumericLevel = getNumericLevel(nextLevel.key);

            if (currentNumericLevel !== null && nextNumericLevel !== null) {
                if (currentNumericLevel === nextNumericLevel) {
                    return currentLevel.index - nextLevel.index;
                }
                return currentNumericLevel - nextNumericLevel;
            }

            if (currentNumericLevel !== null) {
                return -1;
            }

            if (nextNumericLevel !== null) {
                return 1;
            }

            return currentLevel.index - nextLevel.index;
        });

    sortedLevels.forEach(({ key, range }) => {
        temp.push(<VolumePricing key={key} data={data} price={range} />);
    });
    return temp;
};

const VolumePricingCard = ({ editions, data }) => {
    const { mediumDown: isMobile } = useResponsive();
    const [visibleEdition, setVisibleEdition] = useState(null);

    const editionsDataStore = Array.isArray(data?.editionsDataStore) ? data.editionsDataStore : [];

    const getEditionByRefId = editionRefId => editionsDataStore.find(
        edition => edition.productEditionRefId === editionRefId
    );

    const visibleEditions = Array.isArray(editions)
        ? editions.filter(item => !!getEditionByRefId(item.id))
        : [];

    const hasEditions = visibleEditions.length > 0;

    const showEdition = (item, index) => {
        let shouldShowEdition = true;
        if (isMobile) {
            shouldShowEdition = visibleEdition === index;
        }
        const pricing = pricingPlans(item.pricing.pricingPlans);

        return shouldShowEdition ? (
            <div {...n('discountLevels').props}>
                {volumePricingLevel(pricing, data)}
            </div>
        ) : null;
    };

    const getEditionNameByRefId = editionRefId => {
        const hasEdition = getEditionByRefId(editionRefId);
        return hasEdition && hasEdition.name;
    };

    const toggleVisibleEdition = index => {
        index === visibleEdition ? setVisibleEdition(null) : setVisibleEdition(index);
    };

    const angleDirection = index => (visibleEdition === index ? 'angleUp' : 'angleDown');

    return (
        hasEditions
            ? visibleEditions.map((item, index) => (
                <div {...n('wrapper').props} key={item.id} data-testid="volumePricingCard">
                    <div
                        {...n('header').props}
                        onClick={() => isMobile && toggleVisibleEdition(index)}
                        onKeyDown={() => isMobile && toggleVisibleEdition(index)}
                    >
                        {getEditionNameByRefId(item.id)}
                        {isMobile && <Icon type={angleDirection(index)} className="volumePricingCardIcon" /> }
                    </div>
                    { showEdition(item, index) }
                </div>
            ))
            : null
    );
};

VolumePricingCard.propTypes = {
    editions: PropTypes.array,
    data: PropTypes.object
};

VolumePricingCard.defaultProps = {
    editions: [],
    data: {}
};

export default VolumePricingCard;
