import React, { useEffect, useState } from "react";
import { MobileDatePicker } from '@mui/x-date-pickers/MobileDatePicker';
import { PieChart } from '@mui/x-charts/PieChart'; // Importez le composant PieChart
import dayjs from 'dayjs';


const Pourcentage = () => {
  const [value, setValue] = useState(dayjs());
  const [data, setData] = useState([]);
  const [MilkPourcentage, setMilkPourcentage] = useState(0);
  const [CoffeePourcentage, setCoffeePourcentage] = useState(0);
  const [JuicePourcentage, setJuicePourcentage] = useState(0);

  useEffect(() => {
    fetchData();
  }, []);

  const fetchData = async () => {
    try {
      const response = await fetch('http://192.168.1.3:5000/data');
      const responseData = await response.json();
      setData(responseData);
    } catch (error) {
      console.error('Error fetching data:', error);
    }
  };

  const handleSearch = () => {
    if (value) {
      calculatePourcentageByDay(value);
    }
  };

  const calculatePourcentageByDay = (selectedDate) => {
    if (data.length > 0) {
      const selectedDay = selectedDate.$D;
      const selectedMonth = selectedDate.$M;
      const selectedYear = selectedDate.$y;

      const filteredData = data.filter(
        (item) =>
          new Date(item.date).getDate() === selectedDay &&
          new Date(item.date).getMonth() === selectedMonth &&
          new Date(item.date).getFullYear() === selectedYear
      );

      const totalCount = filteredData.length;
      if (totalCount === 0) {
        // Si aucune donnée ne correspond à la date sélectionnée, définissez tous les pourcentages à 0
        setMilkPourcentage(0);
        setCoffeePourcentage(0);
        setJuicePourcentage(0);
      } else {
        const coffeeCount = filteredData.filter(
          (item) => item.category === 'Coffee'
        ).length;
        const juiceCount = filteredData.filter(
          (item) => item.category === 'Juice'
        ).length;
        const milkCount = filteredData.filter(
          (item) => item.category === 'Milk'
        ).length;

        const newCoffeePourcentage = Math.floor((coffeeCount / totalCount) * 100);
        const newJuicePourcentage = Math.floor((juiceCount / totalCount) * 100);
        const newMilkPourcentage = Math.floor((milkCount / totalCount) * 100);

        setMilkPourcentage(newMilkPourcentage);
        setCoffeePourcentage(newCoffeePourcentage);
        setJuicePourcentage(newJuicePourcentage);
      }
    }
  };



  const getArcLabel = (params) => {
    return `${params.value}%`; // Concaténez le symbole "%" à la valeur du pourcentage
  };

  return (
    
    <div className="p-4 h-screen relative" style={{ background: "#e8f0fb" }}>
     
     
    <div className=" w-full h-[72%] absolute rounded-[8000px] bg-[#15406d] z-0  mt-[-55%] ml-[-5%] mr-[5%]  "></div>
    <div className="">
    <div className="  z-0 flex justify-center ">
      <MobileDatePicker
      
        
        
        slotProps={{
          textField: {
            color:'primary',
            sx: {
              color: '#F2294E',
              borderRadius: '20px',
              borderWidth: '4px',
              borderColor: '#FFFFFF',
              border: '2px solid',
              backgroundColor: '#F2294E',
            }
          }
        }} 
        value={value}
        onChange={(newValue) => setValue(newValue)}
        onAccept={handleSearch} // Déclenche la recherche lorsque l'utilisateur accepte la date
      />
    </div>
    </div>
    <div className="flex ">
      <div className="w-full bg-[#f9fafe] z-0 rounded-2xl shadow-lg mx-4 mt-5"  key="coffee">
      <PieChart
      series={[
        {
          data: [
            { id: 0, value: MilkPourcentage, label: 'Milk' },
            { id: 1, value: CoffeePourcentage, label: 'Coffee' },
            { id: 2, value: JuicePourcentage, label: 'Juice' },
          ],
        },
      ]}
      width={400}
      height={200}
    />
      </div>
    </div>
  </div>
  
  );
};

export default Pourcentage;