import React, { useEffect, useRef } from 'react';
import * as d3 from 'd3';

const BarChart = ({ data }) => {
    const d3Chart = useRef();

    const drawChart = () => {
        const margin = { top: 50, right: 40, bottom: 70, left: 60 };
        const width = 1000 - margin.left - margin.right;
        const height = 500 - margin.top - margin.bottom;

        d3.select(d3Chart.current).select("svg").remove();

        const svg = d3.select(d3Chart.current)
            .append("svg")
            .attr("width", width + margin.left + margin.right)
            .attr("height", height + margin.top + margin.bottom)
            .append("g")
            .attr("transform", `translate(${margin.left}, ${margin.top})`);

        const x = d3.scaleBand()
            .range([0, width])
            .padding(0.1);
        const y = d3.scaleLinear()
            .range([height, 0]);

        x.domain(data.map(d => d.date));
        y.domain([0, d3.max(data, d => d.occurrences)]);

        svg.selectAll(".bar")
            .data(data)
            .enter().append("rect")
            .attr("class", "bar")
            .attr("width", x.bandwidth())
            .attr("x", d => x(d.date))
            .attr("y", d => y(d.occurrences))
            .attr("height", d => height - y(d.occurrences));

        // Axe X
        svg.append("g")
            .attr("transform", `translate(0, ${height})`)
            .call(d3.axisBottom(x))
            .selectAll("text")
            .attr("transform", "rotate(-45)")
            .style("text-anchor", "end");

        // axe Y
        svg.append("g")
            .call(d3.axisLeft(y));

        // titre axe X
        svg.append("text")
            .attr("x", width / 2 )
            .attr("y", height + margin.bottom - 20)
            .style("text-anchor", "middle")
            .text("Date");

        // tiitre Axe Y
        svg.append("text")
            .attr("transform", `rotate(-90)`)
            .attr("y", 0)
            .attr("x",0 - (height / 2))
            .attr("dy", "-1em")
            .style("text-anchor", "middle")
            .text("Nombre de ventes");
    };

    useEffect(() => {
        if (data && data.length > 0) {
            drawChart();
        }
    }, [data]);

    return <div ref={d3Chart} />;
};

export default BarChart;
