import { jsx as _jsx } from "react/jsx-runtime";
import { useRef, useEffect } from "react";
import { Svg, Wrapper } from "./d3-donut.styled";
import * as d3 from "d3";
const PADDING = 10;
const COLOR_RANGE = ["#8FBFF8", "#61ADFF", "#125299"];
const PAYLOAD = [
    { name: "a", value: 33 },
    { name: "b", value: 33 },
    { name: "c", value: 33 },
];
const D3DonutChart = ({ className, colorRange, innerRadius, onPathMouseOut, onPathMouseOver, outerRadius, payload, side, }) => {
    const svgRef = useRef(null);
    const total = payload.reduce((acc, { value }) => acc + value, 0);
    const isEmpty = !payload ||
        !colorRange ||
        payload.length === 0 ||
        colorRange.length === 0 ||
        total <= 0;
    const data = isEmpty ? PAYLOAD : payload;
    const colors = isEmpty ? COLOR_RANGE : colorRange;
    useEffect(() => {
        if (!svgRef.current)
            return;
        const svg = d3.select(svgRef.current);
        // @ts-expect-error
        svg.attr("viewBox", [
            -(side + PADDING) / 2,
            -(side + PADDING) / 2,
            side + PADDING,
            side + PADDING,
        ]);
        const colorScale = d3
            .scaleOrdinal()
            .domain(data.map((el) => el.name))
            .range(colors);
        const pie = d3
            .pie()
            .padAngle(0.005)
            .sort(null)
            .value((d) => d.value);
        const radius = side / 2;
        const arc = d3
            .arc()
            .innerRadius(innerRadius ?? radius * 0.67)
            .outerRadius(outerRadius ?? radius - 1);
        const arcs = pie(data);
        svg
            .selectAll("path")
            .data(arcs)
            .join("path")
            .attr("fill", (d) => colorScale(d.data.name))
            .transition()
            .duration(1000)
            .attr("d", arc);
        svg
            .selectAll("path")
            .on("mouseover", (e) => e.target.__data__?.data &&
            onPathMouseOver &&
            onPathMouseOver(e.target.__data__.data))
            .on("mouseout", () => onPathMouseOut && onPathMouseOut());
    }, [
        colors,
        data,
        innerRadius,
        onPathMouseOut,
        onPathMouseOver,
        outerRadius,
        side,
    ]);
    return (_jsx(Wrapper, { className: `ui-d3donut__wrapper ${className ?? ""}`, children: _jsx(Svg, { className: `ui-d3donut__svg ${isEmpty ? "rotate" : ""}`, style: { height: side, width: side }, ref: svgRef }) }));
};
export default D3DonutChart;
//# sourceMappingURL=d3-donut.js.map