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

interface DataPoint {
  year: number;
  value: number;
}

function Diagrams_Metre_Carre() {
  const chartRef = useRef<SVGSVGElement>(null);

  // Données
  const data: DataPoint[] = [
    { year: 2018, value: 21050 },
    { year: 2019, value: 28203 },
    { year: 2020, value: 27420 },
    { year: 2021, value: 24128 },
    { year: 2022, value: 38806 },
    { year: 2023, value: 12999 },
  ];

  useEffect(() => {
    // Declare the chart dimensions and margins.
    const width = 640;
    const height = 400;
    const marginTop = 20;
    const marginRight = 20;
    const marginBottom = 30;
    const marginLeft = 40;

    // Declare the x (horizontal position) scale.
    const x = d3.scaleTime()
      .domain([new Date("2018-01-01"), new Date("2023-01-01")])
      .range([marginLeft, width - marginRight]);

    // Declare the y (vertical position) scale.
    const y = d3.scaleLinear()
      .domain([0, d3.max(data, d => d.value)!]) // Use ! to assert that it's not undefined
      .range([height - marginBottom, marginTop]);

    // Create the SVG container.
    const svg = d3.select(chartRef.current)
      .attr("width", width)
      .attr("height", height);

    // Add the x-axis.
    svg.append("g")
      .attr("transform", `translate(0,${height - marginBottom})`)
      .call(d3.axisBottom(x).ticks(d3.timeYear.every(1)).tickFormat(d3.timeFormat("%Y")));

    // Add the y-axis.
    svg.append("g")
      .attr("transform", `translate(${marginLeft},0)`)
      .call(d3.axisLeft(y));

    // Add the line.
    const line = d3.line<DataPoint>()
      .x(d => x(new Date(`${d.year}-01-01`))!)
      .y(d => y(d.value));

    svg.append("path")
      .datum(data)
      .attr("fill", "none")
      .attr("stroke", "steelblue")
      .attr("stroke-width", 2)
      .attr("d", line);
  }, [data]); // Re-render when data changes.

  return <svg ref={chartRef} />;
}

export default Diagrams_Metre_Carre;
