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

import BarChartSVG, { BarChartSVGProps } from './BarChartSVG';
import { useTooltip } from '../../hooks/useTooltip';
import { ChartData } from '../../utils/data';

type BarChartWithTooltipProps = BarChartSVGProps & {
  showTooltip?: boolean;
  tooltipComponent?: (data: ChartData) => JSX.Element;
};

export const BarChartWithTooltip = (props: BarChartWithTooltipProps) => {
  const { showTooltip, tooltipComponent, ...chartProps } = props;
  const { bindTooltip, renderTooltip } = useTooltip<ChartData>(
    Boolean(showTooltip)
  );

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

BarChartWithTooltip.defaultProps = {
  showTooltip: true,
  tooltipComponent: (data) => <Tooltip data={data} />,
} as Partial<BarChartWithTooltipProps>;

type BarChartProps = WithContainerProps<BarChartWithTooltipProps>;

export const BarChart = (props: BarChartProps) => {
  return (
    <ChartContainer
      chart={({ width, height }) => {
        if (width === 0 || height === 0) return null;
        const chartProps = Object.assign({}, { width, height }, props);
        return <BarChartWithTooltip {...chartProps} />;
      }}
    />
  );
};
