import { Tooltip, TooltipData } from '../../common/Tooltip';
import { LegendOrdinal } from '../../common/LegendComponent';
import {
  ChartContainer,
  WithLegendContainerProps,
} from '../../common/ChartContainer';
import { call } from '../../utils';

import BarStackChartSVG, { BarStackChartSVGProps } from './BarStackChartSVG';
import { itemsSelector, labelSelector } from '../../utils/data';
import { useTooltip } from '../../hooks/useTooltip';

type BarStackChartWithTooltipProps = BarStackChartSVGProps & {
  showTooltip: boolean;
  tooltipComponent: (data: TooltipData) => JSX.Element;
};

export const BarStackChartWithTooltip = (
  props: BarStackChartWithTooltipProps
) => {
  const { showTooltip, tooltipComponent, ...chartProps } = props;
  const { bindTooltip, renderTooltip } = useTooltip(Boolean(showTooltip));

  return (
    <>
      <BarStackChartSVG bindTooltip={bindTooltip} {...chartProps} />
      {renderTooltip(tooltipComponent)}
    </>
  );
};

BarStackChartWithTooltip.defaultProps = {
  showTooltip: true,
  tooltipComponent: (data) => <Tooltip data={data} />,
} as BarStackChartWithTooltipProps;

type BarStackChartProps = WithLegendContainerProps<BarStackChartWithTooltipProps>;

export const BarStackChart = (props: BarStackChartProps) => {
  const { legendPlacement, legendComponent, ...restProps } = props;
  props.data;

  return (
    <ChartContainer
      chart={({ width, height }) => {
        if (width === 0 || height === 0) return null;
        const chartProps = Object.assign({}, { width, height }, restProps);
        return <BarStackChartWithTooltip {...chartProps} />;
      }}
      legendComponent={call(legendComponent, restProps)}
      legendPlacement={legendPlacement}
    />
  );
};

BarStackChart.defaultProps = {
  legendPlacement: 'bottom',
  legendComponent: (props) => {
    const keys = itemsSelector(props.data[0]).map(labelSelector);
    return <LegendOrdinal keys={keys} />;
  },
} as BarStackChartProps;
