import { jsx as _jsx } from "react/jsx-runtime";
import { useRef, useState, useEffect } from "react";
import * as d3 from "d3";
import { Svg, Wrapper } from "./styled";
const D3BarChart = ({ width, height, padding, color, tickCount, payload, mapFn, ...props }) => {
    const svgRef = useRef(null);
    const barPadding = 1;
    const [serie, setSerie] = useState([]);
    useEffect(() => {
        if (payload && Array.isArray(payload)) {
            const serieNext = payload.map(mapFn);
            setSerie(serieNext);
        }
    }, [payload]);
    useEffect(() => {
        if (!svgRef.current)
            return;
        if (serie.length === 0)
            return;
        const [minX, maxX] = d3.extent(serie);
        if (!minX || !maxX)
            return;
        const svg = d3.select(svgRef.current);
        const xScale = d3
            .scaleLinear()
            .domain([minX, maxX])
            .rangeRound([padding, width - padding]);
        const xScaleDomain = xScale.domain();
        if (!xScaleDomain)
            return;
        const histogram = d3
            .bin()
            .domain(xScaleDomain)
            .thresholds(xScale.ticks(tickCount));
        const bins = histogram(serie);
        var yScale = d3
            .scaleLinear()
            // @ts-ignore
            .domain([0, d3.max(bins, (d) => d.length)])
            .range([height - padding, padding]);
        const xAxis = d3
            .axisBottom(xScale)
            .tickSize(-height + 2 * padding)
            .tickSizeOuter(0);
        const yAxis = d3
            .axisLeft(yScale)
            .tickSize(-width + 2 * padding)
            .tickSizeOuter(0);
        const rect = svg.selectAll("rect").data(bins);
        svg
            .append("g")
            .call(xAxis)
            .attr("transform", "translate(0, " + (height - padding) + ")");
        svg
            .append("g")
            .call(yAxis)
            .attr("transform", "translate(" + padding + ", 0)");
        rect.exit().remove();
        rect
            .enter()
            .append("rect")
            // @ts-ignore
            .attr("x", (d) => xScale(d.x0))
            .attr("y", (d) => yScale(d.length))
            .attr("height", (d) => height - padding - yScale(d.length))
            // @ts-ignore
            .attr("width", (d) => xScale(d.x1) - xScale(d.x0) - barPadding)
            .attr("fill", color);
    }, [svgRef, serie]);
    return (_jsx(Wrapper, { className: "ui-d3barchart__wrapper", children: _jsx(Svg, { className: "ui-d3barchart__svg", style: { height, width }, ref: svgRef }) }));
};
export default D3BarChart;
//# sourceMappingURL=index.js.map