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

import RadarChartSVG, { RadarChartSVGProps } from './RadarChartSVG';
import { RadarChartTooltip, RadarChartTooltipData } from './RadarChartTooltip';
import { call } from '../../utils';
import { ChartNestedData, groupSelector } from '../../utils/data';
import { useTooltip } from '../../hooks/useTooltip';

const RadarChartLegend = ({ data, ...props }: { data: ChartNestedData[] }) => {
  const keys = data.map(groupSelector);
  return <LegendOrdinal keys={keys} {...props} />;
};

type RadarChartWithTooltipProps = RadarChartSVGProps & {
  showTooltip?: boolean;
  tooltipComponent: (data: RadarChartTooltipData[]) => JSX.Element;
};

export const RadarChartWithTooltip = (props: RadarChartWithTooltipProps) => {
  const { showTooltip, tooltipComponent, ...chartProps } = props;
  const { bindTooltip, renderTooltip } = useTooltip<RadarChartTooltipData[]>(
    Boolean(showTooltip)
  );

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

RadarChartWithTooltip.defaultProps = {
  showTooltip: true,
  tooltipComponent: (data) => <RadarChartTooltip data={data} />,
} as RadarChartWithTooltipProps;

type RadarChartProps = WithLegendContainerProps<RadarChartWithTooltipProps>;

export const RadarChart = (props: RadarChartProps) => {
  const { legendPlacement, legendComponent, ...chartProps } = props;

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

RadarChart.defaultProps = {
  legendPlacement: 'bottom',
  legendComponent: (props) => <RadarChartLegend data={props.data} />,
} as RadarChartProps;
