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

import LineChartSVG, { LineChartSVGProps } from './LineChartSVG';
import { call } from '../../utils';
import { groupSelector } from '../../utils/data';
import { useTooltip } from '../../hooks/useTooltip';

type LineChartWithTooltipProps = Omit<LineChartSVGProps, 'onHover'> & {
  showTooltip?: boolean;
  tooltipComponent: (data: LinesTooltipData[]) => JSX.Element;
};

export const LineChartWithTooltip = (props: LineChartWithTooltipProps) => {
  const { showTooltip, tooltipComponent, ...chartProps } = props;
  const { setTooltip, renderTooltip } = useTooltip(Boolean(showTooltip));

  return (
    <>
      <LineChartSVG
        onHover={showTooltip ? setTooltip : undefined}
        {...chartProps}
      />
      {renderTooltip(tooltipComponent)}
    </>
  );
};

LineChartWithTooltip.defaultProps = {
  showTooltip: true,
  tooltipComponent: (data) => <LinesTooltip data={data} />,
} as LineChartWithTooltipProps;

type LineChartProps = WithLegendContainerProps<LineChartWithTooltipProps>;

export const LineChart = (props: LineChartProps) => {
  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 <LineChartWithTooltip {...otherProps} />;
      }}
      legendComponent={call(legendComponent, chartProps)}
      legendPlacement={legendPlacement}
    />
  );
};

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