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

import ParetoChartSVG, {
  ParetoChartSVGProps,
  defaultProps,
} from './ParetoChartSVG';
import { useTooltip } from '../../hooks/useTooltip';
import { LegendItem } from '../../common/LegendComponent';
import { call } from '../../utils';

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

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

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

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

// type ParetoChartProps = WithContainerProps<ParetoChartWithTooltipProps>;
type ParetoChartProps = WithLegendContainerProps<ParetoChartWithTooltipProps>;

export const ParetoChart = (props: ParetoChartProps) => {
  const { legendPlacement, legendComponent, ...restProps } = props;
  return (
    <ChartContainer
      chart={({ width, height }) => {
        const chartProps = Object.assign({}, { width, height }, restProps);
        return <ParetoChartWithTooltip {...chartProps} />;
      }}
      legendComponent={call(legendComponent, restProps)}
      legendPlacement={legendPlacement}
    />
  );
};

ParetoChart.defaultProps = {
  legendPlacement: 'bottom',
  legendComponent: ({
    barLabel,
    barColor = defaultProps.barColor,
    lineLabel,
    lineColor = defaultProps.lineColor,
  }) => {
    return (
      <div className="infografika infografika-legend">
        {barLabel && <LegendItem color={barColor} label={barLabel} />}
        {lineLabel && <LegendItem color={lineColor} label={lineLabel} />}
      </div>
    );
  },
} as ParetoChartProps;
