import React, { FC } from 'react';
import * as Highcharts from 'highcharts';
import HighchartsReact from 'highcharts-react-official';
import { formatMessage } from '@orchard/frontend-localization';
import { DemographicsBreakdownAge, hasAnyValue } from 'src/selectors';
import { CHART_TYPE, DEMOGRAPHIC_AGE_CATEGORIES_VALUES } from 'src/constants/demographics';
import { getDemographicsChartOptions } from 'src/utils/chart';
import { AnalyticsIcon } from '@orchard/frontend-react-components';

export const TERM_UNKNOWN = 'sourceOfStreams.unknown';
export const TERM_BY_AGE = 'topAudience.byAge';
export const CLASSNAME = 'TopAudienceByAge';
export const TEST_ID = CLASSNAME;
export const CLASSNAME_EMPTY_CONTENT = `${CLASSNAME}-empty-content`;

export const EMPTY_MESSAGE = 'error.noData.message';

export interface Props {
    series: DemographicsBreakdownAge[];
}

const createChartOptions = (series: DemographicsBreakdownAge[]) => {
    const chartOptions: Highcharts.Options = getDemographicsChartOptions({
        plotOptions: {
            [CHART_TYPE]: {
                pointWidth: 16 - 2 * series.length,
            }
        },
        series: series.map(({ _17, _18_22, _23_27, _28_34, _35_44, _45_59, _60_, UNKNOWN }, colorIndex) => ({
            type: CHART_TYPE,
            data: [_17, _18_22, _23_27, _28_34, _35_44, _45_59, _60_, UNKNOWN].map(({ percentValue }, x) => ({
                x,
                y: percentValue ? percentValue * 100 : undefined,
                colorIndex,
            }))
        })),
        xAxis: {
            categories: [
                ...DEMOGRAPHIC_AGE_CATEGORIES_VALUES,
                formatMessage(TERM_UNKNOWN),
            ],
        },
        yAxis: {
            max: hasAnyValue(series) ? null : 100,
        },
    });
    return chartOptions;
};

const TopAudienceByAge: FC<Props> = ({ series }) => {
    const chartOptions = createChartOptions(series);
    const noData = series && series.length > 0 && hasAnyValue(series) === false;

    return (
        <div className={CLASSNAME} data-testid={TEST_ID}>
            <h5 className={`${CLASSNAME}-title`}>
                {formatMessage(TERM_BY_AGE)}
            </h5>
            {noData ? (
                <div className={`${CLASSNAME}-empty-content`}>
                    <HighchartsReact highcharts={Highcharts} options={chartOptions} />
                    <div className={`${CLASSNAME}-empty-icon`}>
                        <AnalyticsIcon />
                        <div className={`${CLASSNAME}-empty-message`}>
                            {formatMessage(EMPTY_MESSAGE)}
                        </div>
                    </div>
                </div>
            )
                : <HighchartsReact highcharts={Highcharts} options={chartOptions} />}
        </div>
    );
};

export default TopAudienceByAge;
