import React, { useState, useEffect } from "react";
import { Doughnut } from "react-chartjs-2";
import { Chart, ArcElement } from "chart.js";
import { MenuItem, Select, FormControl } from "@mui/material";
import styles from "./ParticipationChart.module.css";
import getAllEvents from "../../../../utils/events/getAllEvents.js";

Chart.register(ArcElement);

function ParticipationChart() {
  const [selected, setSelected] = useState("3");

  const [eventsCount, setEventsCount] = useState(0); 
  const [participationRate, setParticipationRate] = useState(0);

  useEffect(() => {
    const fetchEvents = async () => {
      const res = await getAllEvents();

      const eventsArray = res?.data ?? [];

      setEventsCount(eventsArray.length);

      const rate = Math.min(eventsArray.length, 100);
      setParticipationRate(rate);
    };

    fetchEvents();
  }, []);

  const chartData = {
    labels: ["Progress", "Background"],
    datasets: [
      {
        data: [participationRate, 100 - participationRate],
        backgroundColor: ["#1e60f9ff", "#ffffffff"],
        borderWidth: 0,
        cutout: "93%",
        rotation: -90,
      },
    ],
  };

  const chartOptions = {
    responsive: true,
    plugins: {
      legend: { display: false },
      tooltip: { enabled: false },
    },
  };

  return (
    <div className={`${styles.leftBlock} glassCard`}>
      <div className={styles.participationHeader}>
        <div className={`${styles.partiText} glassCard`}>
          <label>Taux de participation depuis :</label>

          <FormControl className={styles.formDesign}>
            <Select
              value={selected}
              onChange={(e) => setSelected(e.target.value)}
              className={styles.selectRoot}
            >
              <MenuItem value="1">1 mois</MenuItem>
              <MenuItem value="3">3 mois</MenuItem>
              <MenuItem value="6">6 mois</MenuItem>
              <MenuItem value="12">12 mois</MenuItem>
            </Select>
          </FormControl>
        </div>
      </div>

      <div className={styles.chartContainer}>
        <div className={styles.chartWrapper}>
          <Doughnut data={chartData} options={chartOptions} />
          <div className={styles.chartPercentage}>
            {eventsCount} events
          </div>
        </div>
      </div>
    </div>
  );
}

export default ParticipationChart;
