import React, { useState } from 'react';
import PropTypes from 'prop-types';
import { createNamespace } from '../../tools/namingTools';
import { useResponsive } from '../../tools/widths/useResponsive';
import './styles/VolumePricingCard.scss';
import VolumePricing from '../volume-pricing/VolumePricing';
import Icon from '../icon/Icon';

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 volumePricingLevel = (pricingMap, data) => {
    const temp = [];
    Object.entries(pricingMap).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 hasEditions = Array.isArray(editions) && editions.length;

    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 = data.editionsDataStore.find(
            edition => edition.productEditionRefId === editionRefId
        );
        return hasEdition && hasEdition.name;
    };

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

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

    return (
        hasEditions
            ? editions.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;
