import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useState } from 'react';
import { Bar, BarChart, CartesianGrid, ReferenceLine, ResponsiveContainer, Tooltip, XAxis, YAxis, } from 'recharts';
import styled, { useTheme } from 'styled-components';
import { spacing, Stack, Wrap } from '../../spacing';
import { chartColors, fontSize } from '../../style/theme';
import { Box } from '../box/Box';
import { ConstrainedText } from '../constrainedtext/Constrainedtext.component';
import { IconHelp } from '../iconhelper/IconHelper';
import { Loader } from '../loader/Loader.component';
import { Text } from '../text/Text.component';
import { renderTooltipContent, useChartData } from './utils';
const CHART_CONSTANTS = {
    TICK_WIDTH_OFFSET: 5,
    BAR_SIZE: 12,
    MIN_POINT_SIZE: 1,
    DEFAULT_HEIGHT: 200,
    CHART_MARGIN: {
        left: 0,
        right: 0,
        top: 0,
        bottom: 0,
    },
};
/* ---------------------------------- COMPONENTS ---------------------------------- */
const CustomTick = ({ x, y, payload, visibleTicksCount, width, }) => {
    const theme = useTheme();
    const tickWidth = width / visibleTicksCount - CHART_CONSTANTS.TICK_WIDTH_OFFSET;
    const centerX = x - tickWidth / 2;
    return (_jsx("foreignObject", { x: centerX, y: y, width: tickWidth, color: theme.textSecondary, overflow: "visible", children: _jsx(ConstrainedText, { text: _jsx(Text, { variant: "Smaller", color: "textSecondary", children: String(payload.value) }), centered: true, tooltipStyle: {
                backgroundColor: theme.backgroundLevel1,
                padding: spacing.r10,
                borderRadius: spacing.r8,
                border: `1px solid ${theme.border}`,
                position: 'absolute',
            } }) }));
};
const StyledResponsiveContainer = styled(ResponsiveContainer) `
  // Avoid tooltip over constrained text to be cut off
  & .recharts-surface {
    overflow: visible;
  }
`;
const ChartHeader = ({ title, secondaryTitle, helpTooltip, rightTitle, }) => {
    return (_jsxs(Wrap, { children: [_jsxs(Stack, { gap: "r4", children: [_jsx(Text, { variant: "ChartTitle", children: title }), helpTooltip && (_jsx(IconHelp, { tooltipMessage: helpTooltip, title: helpTooltip })), secondaryTitle && (_jsx(Text, { color: "textSecondary", style: {
                            marginLeft: spacing.r8,
                        }, children: secondaryTitle }))] }), rightTitle && _jsx(Text, { children: rightTitle })] }));
};
const Loading = ({ height }) => {
    return (_jsx(Box, { height: height, style: {
            alignItems: 'center',
            justifyContent: 'center',
            display: 'flex',
        }, children: _jsx(Loader, { size: "larger", children: _jsx(Text, { children: "Loading Chart Data..." }) }) }));
};
/* ---------------------------------- MAIN COMPONENT ---------------------------------- */
export const Barchart = (props) => {
    const theme = useTheme();
    const [hoveredValue, setHoveredValue] = useState();
    const { height = CHART_CONSTANTS.DEFAULT_HEIGHT, bars, type = 'category', colorSet, unitRange, stacked, defaultSort, tooltip, title, secondaryTitle, helpTooltip, rightTitle, isLoading, } = props;
    const { rechartsBars, unitLabel, roundReferenceValue, rechartsData } = useChartData(bars, type, colorSet, stacked, defaultSort, unitRange);
    return (_jsxs(Stack, { direction: "vertical", gap: "r8", children: [_jsx(ChartHeader, { title: title, secondaryTitle: secondaryTitle, helpTooltip: helpTooltip, rightTitle: rightTitle }), isLoading ? (_jsx(Loading, { height: height })) : (_jsx(StyledResponsiveContainer, { width: "100%", height: height, children: _jsxs(BarChart, { data: rechartsData, accessibilityLayer: true, barSize: CHART_CONSTANTS.BAR_SIZE, height: height, margin: CHART_CONSTANTS.CHART_MARGIN, children: [_jsx(CartesianGrid, { vertical: false, horizontal: false, fill: theme.backgroundLevel1 }), rechartsBars.map((bar) => {
                            const { fill, dataKey, stackId } = bar;
                            return (_jsx(Bar, { dataKey: dataKey, fill: chartColors[fill] || fill, minPointSize: CHART_CONSTANTS.MIN_POINT_SIZE, stackId: stackId, onMouseOver: () => setHoveredValue(dataKey), onMouseLeave: () => setHoveredValue(undefined) }, dataKey));
                        }), _jsx(YAxis, { tickCount: 1, unit: ` ${unitLabel}`, domain: [0, roundReferenceValue], tickFormatter: (value) => new Intl.NumberFormat('fr-FR').format(value.toFixed(0)) // Add a space as thousand separator
                            , axisLine: false, tick: {
                                fill: theme.textSecondary,
                                fontSize: fontSize.smaller,
                            }, tickLine: false, label: {
                                fill: theme.textSecondary,
                            }, orientation: "right" }), _jsx(ReferenceLine, { y: roundReferenceValue, fill: theme.border, strokeWidth: 0.5 }), _jsx(XAxis, { dataKey: "category", tick: (props) => _jsx(CustomTick, { ...props }), type: "category", interval: 0, allowDataOverflow: true, tickLine: {
                                stroke: theme.textSecondary,
                            }, axisLine: {
                                stroke: theme.textSecondary,
                            } }), _jsx(Tooltip, { content: (props) => renderTooltipContent(props, tooltip, hoveredValue), cursor: false })] }) }))] }));
};
