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

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

import PieChartSVG, { PieChartSVGProps } from './PieChartSVG';
import { labelSelector } from '../../utils/data';
import { useTooltip } from '../../hooks/useTooltip';

type PieChartWithTooltipProps = PieChartSVGProps & {
  showTooltip?: boolean;
  tooltipComponent: (data: TooltipData) => JSX.Element;
};

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

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

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

type PieChartProps = WithLegendContainerProps<PieChartWithTooltipProps>;

export const PieChart = (props: PieChartProps) => {
  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 <PieChartWithTooltip {...chartProps} />;
      }}
      legendComponent={call(legendComponent, restProps)}
      legendPlacement={legendPlacement}
    />
  );
};

PieChart.defaultProps = {
  legendPlacement: 'bottom',
  legendComponent: (props) => {
    const keys = props.data.map(labelSelector);
    return <LegendOrdinal keys={keys} />;
  },
} as PieChartProps;
