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

import TreeMapSVG, { TreeMapSVGProps } from './TreeMapSVG';
import { useTooltip } from '../../hooks/useTooltip';

type TreeMapWithTooltipProps = Omit<TreeMapSVGProps, 'bindTooltip'> & {
  showTooltip?: boolean;
  tooltipComponent: (data: TooltipData) => JSX.Element;
};

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

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

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

type TreeMapProps = WithContainerProps<TreeMapWithTooltipProps>;

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