import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useState, useRef, useMemo, useCallback } from 'react';
import { Bar, BarChart as RechartsBarChart, CartesianGrid, Tooltip, XAxis, YAxis, } from 'recharts';
import { useTheme } from 'styled-components';
import { Stack } from '../../../spacing';
import { chartColors, fontSize } from '../../../style/theme';
import { useChartLegend } from '../legend/ChartLegendWrapper';
import { BarchartTooltip } from './BarchartTooltip';
import { formatTickValue, getTicks } from '../common/chartUtils';
import { useChartData } from './Barchart.utils';
import { ChartHeader, ChartError, ChartLoading, CustomTick, StyledResponsiveContainer, } from '../common/SharedComponents';
const CHART_CONSTANTS = {
    TICK_WIDTH_OFFSET: 4,
    BAR_SIZE: 12,
    MIN_POINT_SIZE: 3,
    DEFAULT_HEIGHT: 200,
    CHART_MARGIN: {
        left: 0,
        right: -10,
        top: 0,
        bottom: 0,
    },
};
/* ---------------------------------- MAIN COMPONENT ---------------------------------- */
export const Barchart = (props) => {
    const theme = useTheme();
    const { getColor } = useChartLegend();
    const [hoveredValue, setHoveredValue] = useState();
    const chartRef = useRef(null);
    const { height = CHART_CONSTANTS.DEFAULT_HEIGHT, bars, type = { type: 'category' }, unitRange, stacked, stackedBarSort = 'default', defaultSort, tooltip, title, secondaryTitle, helpTooltip, rightTitle, isLoading, isError, } = props;
    // Create colorSet from ChartLegendWrapper
    const colorSet = useMemo(() => bars === null || bars === void 0 ? void 0 : bars.reduce((acc, bar) => {
        const color = getColor(bar.label);
        if (color) {
            acc[bar.label] = color;
        }
        return acc;
    }, {}), [bars, getColor]);
    const { rechartsBars, unitLabel, roundReferenceValue, rechartsData, topDomain, } = useChartData(bars || [], type, colorSet || {}, stacked, defaultSort, unitRange, stackedBarSort);
    const titleWithUnit = unitLabel ? `${title} (${unitLabel})` : title;
    const tickFormatter = useCallback((value) => formatTickValue(value, roundReferenceValue), [roundReferenceValue]);
    const renderChartContent = () => {
        if (isError || (!bars && !isLoading)) {
            return _jsx(ChartError, { height: height });
        }
        if (isLoading) {
            return _jsx(ChartLoading, { height: height });
        }
        return (_jsx(StyledResponsiveContainer, { ref: chartRef, width: "100%", height: height, children: _jsxs(RechartsBarChart, { data: rechartsData, accessibilityLayer: true, barSize: type.type === 'category'
                    ? type.gap === 0
                        ? undefined
                        : CHART_CONSTANTS.BAR_SIZE
                    : CHART_CONSTANTS.BAR_SIZE, height: height, margin: CHART_CONSTANTS.CHART_MARGIN, barCategoryGap: type.type === 'category' ? type.gap : undefined, children: [_jsx(CartesianGrid, { vertical: true, horizontal: true, verticalPoints: [0], horizontalPoints: [0], stroke: theme.border, fill: theme.backgroundLevel4, strokeWidth: 1 }), rechartsBars.map((bar) => {
                        const { fill, dataKey, stackId } = bar;
                        return (_jsx(Bar, { dataKey: dataKey, fill: chartColors[fill] || fill, minPointSize: stacked ? 0 : CHART_CONSTANTS.MIN_POINT_SIZE, stackId: stackId, isAnimationActive: false, onMouseOver: () => setHoveredValue(dataKey), onMouseLeave: () => setHoveredValue(undefined) }, dataKey));
                    }), _jsx(YAxis, { interval: 0, domain: [0, topDomain], ticks: getTicks(roundReferenceValue, false), tickFormatter: tickFormatter, axisLine: { stroke: theme.border }, tick: {
                            fill: theme.textSecondary,
                            fontSize: fontSize.smaller,
                        }, orientation: "right" }), _jsx(XAxis, { dataKey: "category", tick: (props) => (_jsx(CustomTick, { ...props, type: type, tickWidthOffset: CHART_CONSTANTS.TICK_WIDTH_OFFSET })), type: "category", interval: 0, allowDataOverflow: true, tickLine: {
                            stroke: theme.border,
                        }, axisLine: {
                            stroke: theme.border,
                        } }), _jsx(Tooltip, { content: (props) => (_jsx(BarchartTooltip, { type: type, colorSet: colorSet, tooltipProps: props, hoveredValue: hoveredValue, tooltip: tooltip, unitLabel: unitLabel, chartContainerRef: chartRef })), cursor: false })] }) }));
    };
    return (_jsxs(Stack, { direction: "vertical", style: { gap: '0' }, children: [_jsx(ChartHeader, { title: titleWithUnit, secondaryTitle: secondaryTitle, helpTooltip: helpTooltip, rightTitle: rightTitle }), renderChartContent()] }));
};
