import { memo } from 'react';

import { Pie } from '@visx/shape';
import { Group } from '@visx/group';

import { valueSelector, ChartData } from '../../utils/data';
import { call, interpolate } from '../../utils';
import { format } from '../../utils/format';
import { COLORS } from '../../config';
import { TextLabelSettings } from '../../types';
import { TooltipBinder } from '../../hooks/useTooltip';

export type PieChartSVGProps = TextLabelSettings & {
  data: ChartData[];
  width: number;
  height: number;
  colors?: string[];
  padAngle?: number;
  padRadius?: number;
  cornerRadius?: number;
  outerRadius?: number;
  innerRadius?: number;
  valueFormat?: string;

  onClick?: (
    data: ChartData,
    i: number,
    ev: React.MouseEvent<SVGGElement, MouseEvent>
  ) => void;
  bindTooltip?: TooltipBinder<ChartData>;
};

export const defaultProps = {
  colors: COLORS,
  outerRadius: 1,
  innerRadius: 0,
  textLabel: true,
  textLabelSize: 12,
};

function PieChartSVG({
  data,
  width,
  height,
  colors,
  padAngle,
  padRadius,
  cornerRadius,
  outerRadius,
  innerRadius,
  valueFormat,
  textLabel,
  textLabelSize,
  textLabelColor,
  onClick,
  bindTooltip,
}: PieChartSVGProps & typeof defaultProps) {
  const radius = Math.min(width, height) / 2;
  const outerRadiusValue = interpolate(outerRadius, 0, 1, 0, radius);
  const innerRadiusValue = interpolate(innerRadius, 0, 1, 0, radius);

  // const colorScale = scaleLinear({
  //   domain: [
  //     Math.min(...data.map(valueSelector)),
  //     Math.max(...data.map(valueSelector)),
  //   ],
  //   range: COLORS,
  // });
  const colorScale = (index: number) => colors[index % colors.length];

  return (
    <svg width={width} height={height}>
      <Group top={height / 2} left={width / 2}>
        <Pie
          // className={string}
          // top={number}
          // left={number}
          data={data}
          pieValue={valueSelector}
          // pieSort={func}
          pieSortValues={() => 1}
          outerRadius={outerRadiusValue}
          innerRadius={innerRadiusValue}
          cornerRadius={cornerRadius}
          padAngle={padAngle}
          padRadius={padRadius}
        >
          {(pie) => {
            return pie.arcs.map((arc, i) => {
              const [centroidX, centroidY] = pie.path.centroid(arc);
              const { startAngle, endAngle } = arc;

              const hasSpaceForLabel = endAngle - startAngle >= 0.25;

              const formattedValue = valueFormat
                ? format(valueFormat, arc.data)
                : String(arc.data.value);

              const handleClick: React.MouseEventHandler<SVGGElement> = (ev) =>
                onClick!(arc.data, i, ev);
              const tooltipProps = call(bindTooltip, arc.data, formattedValue);

              const path = pie.path(arc);
              if (!path) return;

              return (
                <g
                  onClick={onClick && handleClick}
                  {...tooltipProps}
                  key={arc.data.id || i}
                >
                  <path
                    d={path}
                    // fill={colorScale(arc.data.value)}
                    fill={colorScale(i)}
                  />
                  {hasSpaceForLabel && textLabel && (
                    <text
                      x={centroidX}
                      y={centroidY}
                      dy=".33em"
                      fill={textLabelColor}
                      fontSize={textLabelSize}
                      textAnchor="middle"
                    >
                      {formattedValue}
                    </text>
                  )}
                </g>
              );
            });
          }}
        </Pie>
      </Group>
    </svg>
  );
}

PieChartSVG.defaultProps = defaultProps;

export default memo(PieChartSVG);
