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

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

    const isStartOfMonth = (date) => {
        const day = new Date(date).getDate();
        return day === 1;
    };

    const drawChart = () => {
        const colorScale = d3.scaleOrdinal(d3.schemeCategory10);
        const margin = { top: 50, right: 40, bottom: 70, left: 60 };
        const barWidth = 40;
        const maxWidth = window.innerWidth - margin.left - margin.right;
        let chartWidth = data.length * barWidth + 200;

        if (chartWidth > maxWidth) {
            chartWidth = maxWidth;
        }

        const height = 600 - margin.top - margin.bottom;

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

        const svg = d3.select(d3Chart.current)
            .append("svg")
            .attr("width", chartWidth + 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, chartWidth])
            .padding(0.1)
            .domain(data.map(d => d.date));
        const y = d3.scaleLinear()
            .range([height, 0])
            .domain([0, d3.max(data, d => d.occurrences)]);

        let displayedDates = data.length >= 90
            ? data.filter(d => isStartOfMonth(d.date)).map(d => d.date)
            : data.map(d => d.date);

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

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

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

        // Titre Axe X à l'extrémité
        svg.append("text")
            .attr("x", chartWidth + 30)
            .attr("y", height + margin.bottom / 2)
            .style("text-anchor", "end")
            .text("Date");

        // Titre Axe Y à l'extrémité supérieure
        svg.append("text")
            .attr("transform", "rotate(360)")
            .attr("y", 0 - margin.left + 40)
            .attr("x", 0 - margin.top + 80)
            .style("text-anchor", "end")
            .text("Nbr ventes");
    };

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

    return (
        <div style={{ position: 'relative', overflowX: 'auto' }}>
            <div ref={d3Chart}></div>
        </div>
    );
};

export default BarChart;
