import { Bar } from "react-chartjs-2";
import { Chart as ChartJs } from "chart.js/auto";
import { useEffect, useState } from "react";

import { Button, CircularProgress, Typography } from "@mui/material";
import { useSelector } from "react-redux";
import { defaults } from "chart.js";
import { getRoleFromUrl } from "../../utils/getRoleFromUrl";

defaults.font.family = "iranyekan";

console.log(ChartJs);

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

  useEffect(() => {
    fetch(`${province}hatching_age_range/?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);
      });
  }, [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
    },
  };

  return (
    <>
      {loading ? (
        <CircularProgress />
      ) : (
        <>
          <Typography className="header-stats">
            موجودی جوجه ریزی (مانده در سالن) بر اساس بازه سنی
            {(getRoleFromUrl() === "ProvinceOperator" ||
              getRoleFromUrl() === "SuperAdmin") && (
              <a href={`${province}hatching_age_range_excel/`}>
                <Button>دانلود اکسل</Button>
              </a>
            )}
          </Typography>
          <Bar
            style={{ direction: "ltr" }}
            data={dataSample}
            options={options}
          />
        </>
      )}
    </>
  );
};
