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

import ChoroplethSVG, { ChoroplethSVGProps } from './ChoroplethSVG';

import { MAP_COLORS } from '../../config';
import { call } from '../../utils';
import { ChartData, valueSelector } from '../../utils/data';
import { useTooltip } from '../../hooks/useTooltip';

type ChoroplethWithTooltipProps = Omit<ChoroplethSVGProps, 'bindTooltip'> & {
  showTooltip?: boolean;
  tooltipComponent: (data: TooltipData) => JSX.Element;
};

export const ChoroplethWithTooltip = (props: ChoroplethWithTooltipProps) => {
  const { showTooltip, tooltipComponent, ...chartProps } = props;
  const { bindTooltip, renderTooltip } = useTooltip<ChartData>(
    Boolean(showTooltip)
  );

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

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

type ChoroplethProps = WithLegendContainerProps<ChoroplethWithTooltipProps>;

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

Choropleth.defaultProps = {
  colors: MAP_COLORS,
  legendPlacement: 'bottom',
  legendComponent: (props) => {
    const min = Math.min(0, ...props.data.map(valueSelector));
    const max = Math.max(0, ...props.data.map(valueSelector));
    return (
      <div
        style={{
          display: 'flex',
          justifyContent: 'center',
        }}
      >
        <LegendGradient
          min={min}
          max={max}
          colors={props.colors}
          style={{
            width: '50%',
            minWidth: 200,
          }}
        />
      </div>
    );
  },
} as ChoroplethProps;
