import { Line } from "react-chartjs-2";
import { Chart as ChartJs } from "chart.js/auto";
import { useEffect, useState } from "react";
import {
  Button,
  CircularProgress,
  FormControl,
  MenuItem,
  Select,
  Typography,
} from "@mui/material";
import { useSelector } from "react-redux";
import { defaults } from "chart.js";
import { formatJustDate } from "../../utils/formatTime";
import { Grid } from "../../components/grid/Grid";
import { getRoleFromUrl } from "../../utils/getRoleFromUrl";

defaults.font.family = "iranyekan";

console.log(ChartJs);

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

  const [selectedOption, setSelectedOption] = useState(10);

  const handleChange = (event) => {
    setSelectedOption(event.target.value);
  };

  useEffect(() => {
    fetch(
      `${province}number_of_kills/?day=${selectedOption}&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);
      });
  }, [selectedOption, province]);

  const dataSample = {
    labels: data.map((item) => formatJustDate(item.date)),
    datasets: [
      {
        label: "تعداد کشتار",
        data: data.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 />
      ) : (
        <>
          <Grid
            container
            className="header-stats"
            alignItems="center"
            justifyContent="center"
            gap={1}
          >
            <Typography>گزارش تعداد کشتار</Typography>
            <Grid>
              <FormControl variant="outlined">
                <Select value={selectedOption} onChange={handleChange}>
                  <MenuItem value="10">10</MenuItem>
                  <MenuItem value="20">20</MenuItem>
                  <MenuItem value="30">30</MenuItem>
                  <MenuItem value="45">45</MenuItem>
                </Select>
              </FormControl>
            </Grid>
            <Typography>روز گذشته (براساس بار)</Typography>
            <a
              href={`${province}number_of_kills_excel/?day=${selectedOption}&role=${getRoleFromUrl()}&key=${userKey}`}
            >
              <Button>دانلود اکسل</Button>
            </a>
          </Grid>
          <Line
            style={{ direction: "ltr" }}
            data={dataSample}
            options={options}
          />
        </>
      )}
    </>
  );
};
