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

import ScatterChartSVG, { ScatterChartSVGProps } from './ScatterChartSVG';
import {
  ScatterChartTooltip,
  ScatterChartTooltipProps,
} from './ScatterChartTooltip';

import { call } from '../../utils';
import { useTooltip } from '../../hooks/useTooltip';

type ScatterChartWithTooltipProps = ScatterChartSVGProps & {
  showTooltip?: boolean;
  tooltipComponent: (data: ScatterChartTooltipProps['data']) => JSX.Element;
};

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

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

ScatterChartWithTooltip.defaultProps = {
  showTooltip: true,
  tooltipComponent: (data) => <ScatterChartTooltip data={data} />,
} as ScatterChartWithTooltipProps;

type ScatterChartProps = WithLegendContainerProps<ScatterChartWithTooltipProps>;

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

ScatterChart.defaultProps = {
  legendPlacement: 'bottom',
  legendComponent: (props) => {
    const keys = Array.from(new Set(props.data.map((d) => d.label)));
    return <LegendOrdinal keys={keys} />;
  },
} as ScatterChartProps;
