import { Pie } from "react-chartjs-2";
import { Chart as ChartJs } from "chart.js/auto";
import { useEffect, useState } from "react";
import {
  Button,
  CircularProgress,
  FormControl,
  MenuItem,
  Select,
  Tooltip,
  Typography,
} from "@mui/material";
// import { useSelector } from "react-redux";
import { defaults } from "chart.js";
import { useSelector } from "react-redux";
import ChartDataLabels from "chartjs-plugin-datalabels";
import { Grid } from "../../components/grid/Grid";
import { RiFileExcel2Fill } from "react-icons/ri";
import { getRoleFromUrl } from "../../utils/getRoleFromUrl";
import { format } from "date-fns-jalali";

ChartJs.register(ChartDataLabels);

defaults.font.family = "iranyekan";
console.log(ChartJs);

export const HatchingStockCityRemain = ({ province }) => {
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(false);
  const { authToken } = useSelector((state) => state.userSlice);

  // Create a new Date object
  const currentDate = new Date();
  const shamsiDate = format(new Date(currentDate), "M");
  const [selectedMonth, setSelectedMonth] = useState(shamsiDate);

  const handleMonthChange = (event) => {
    setSelectedMonth(event.target.value);
  };

  const months = [
    "فروردین",
    "اردیبهشت",
    "خرداد",
    "تیر",
    "مرداد",
    "شهریور",
    "مهر",
    "آبان",
    "آذر",
    "دی",
    "بهمن",
    "اسفند",
  ];

  const chartData = {
    labels: data.filter((item) => item.percent).map((item) => item.city),
    datasets: [
      {
        label: "جوجه ریزی",
        data: data.filter((item) => item.percent).map((item) => item.percent),
        quantity: data.map((item) => item.quantity),
        backgroundColor: [
          "#FF6384",
          "#36A2EB",
          "#FFCE56",
          "#4CAF50",
          "#9C27B0",
        ],
      },
    ],
  };

  useEffect(() => {
    fetch(
      `${province}doughnut_left_hatching/?month=${selectedMonth}&role=${getRoleFromUrl()}`,
      {
        headers: {
          Authorization: `Bearer ${authToken}`,
        },
      }
    )
      .then((response) => response.json())
      .then((data) => {
        setData(data);
        setLoading(false);
      })
      .catch((error) => {
        console.error("Error fetching data:", error);
        setLoading(false);
      });
  }, [selectedMonth, province]);

  // const dataSample = {
  //   labels: data.filter((item) => item.quantity).map((item) => item.type),
  //   datasets: [
  //     {
  //       label: "تعداد جوجه ریزی",
  //       data: data.filter((item) => item.quantity).map((item) => item.quantity),
  //       backgroundColor: "rgba(75,192,192,0.2)",
  //       borderColor: "rgba(75,192,192,1)",
  //       borderWidth: 1,
  //     },
  //   ],
  // };

  // const options = {
  //   scales: {
  //     y: {
  //       beginAtZero: true,
  //     },
  //   },
  //   plugins: {
  //     rtl: true, // This enables RTL layout
  //   },
  // };

  const options = {
    plugins: {
      legend: {
        display: true,
        position: "bottom",
      },
      tooltip: {
        callbacks: {
          label: (context) => {
            const label = context.label || "";
            const value = context.formattedValue;
            const quantity = context.dataset.quantity[context.dataIndex];
            return `${label}: %${value} - ${quantity?.toLocaleString()} قطعه`;
          },
        },
      },
      datalabels: {
        color: "#fff",
        formatter: (value, context) => {
          const txt = `${
            context.chart.data.labels[context.dataIndex]
          }: ٪${value}`;
          return `${txt}`;
        },
      },
    },
  };

  return (
    <>
      {loading ? (
        <CircularProgress />
      ) : (
        <>
          <Typography className="header-stats">
            <Grid container alignItems="center" gap={2} justifyContent="center">
              گزارش مانده جوجه ریزی بر اساس شهرستان
              <FormControl style={{ width: "120px" }}>
                <Select value={selectedMonth} onChange={handleMonthChange}>
                  {months.map((month, index) => (
                    <MenuItem key={index} value={index + 1}>
                      {month}
                    </MenuItem>
                  ))}
                </Select>
              </FormControl>
              <Tooltip title="خروجی اکسل">
                <a
                  href={`${province}doughnut_left_hatching_excel/?month=${selectedMonth}&token=${authToken}`}
                  rel="noreferrer"
                >
                  <Button color="success">
                    <RiFileExcel2Fill size={32} />
                  </Button>
                </a>
              </Tooltip>
            </Grid>
          </Typography>

          <div
            style={{
              height: "400px",
              width: "600px",
              display: "flex",
              flexDirection: "column",
              justifyContent: "center",
              alignItems: "center",
            }}
          >
            <Pie
              data={chartData}
              options={options}
              style={{ direction: "ltr" }}
            />
          </div>
        </>
      )}
    </>
  );
};
