import { Tooltip } from '../../common/Tooltip';
import { LegendOrdinal } from '../../common/LegendComponent';
import {
  ChartContainer,
  WithContainerProps,
  WithLegendContainerProps,
} from '../../common/ChartContainer';

import BarGroupChartSVG, {
  BarGroupChartSVGProps,
  InnerDatum,
} from './BarGroupChartSVG';
import { call } from '../../utils';
import { itemsSelector, labelSelector } from '../../utils/data';
import { useTooltip } from '../../hooks/useTooltip';

type BarGroupChartWithTooltipProps = BarGroupChartSVGProps & {
  showTooltip?: boolean;
  tooltipComponent?: (data: InnerDatum) => JSX.Element;
};

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

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

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

type BarGroupChartProps = WithLegendContainerProps<BarGroupChartWithTooltipProps>;

export const BarGroupChart = (props: BarGroupChartProps) => {
  const { legendPlacement, legendComponent, ...restProps } = props;

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

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