import React, { useEffect, useState } from "react";
import { Button, CircularProgress, TextField, Typography } from "@mui/material";
import { DatePicker } from "@mui/x-date-pickers";
import { useFormik } from "formik";
import { Grid } from "../../components/grid/Grid";
import { Yup } from "../../lib/yup/yup";
import { addMonths } from "date-fns-jalali";
import { useDispatch, useSelector } from "react-redux";
import { Bar } from "react-chartjs-2";
import moment from "moment/moment";
import { formatJustDate } from "../../utils/formatTime";
import { LOADING_END, LOADING_START } from "../../lib/redux/slices/appSlice";
import { getRoleFromUrl } from "../../utils/getRoleFromUrl";

const validationSchema = Yup.object({
  startDate: Yup.date("تاریخ شروع الزامی است").required(
    "تاریخ شروع الزامی است"
  ),
  endDate: Yup.date("تاریخ شروع الزامی است").required("تاریخ پایان الزامی است"),
  textInput: Yup.string("تاریخ شروع الزامی است").required("سن الزامی است"),
});

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

  const fetchData = () => {
    dispatch(LOADING_START());
    fetch(
      `${province}forecast_hatching_left_over/?date1=${moment(
        formik.values.startDate
      ).format("YYYY-MM-DD")}&date2=${moment(formik.values.endDate).format(
        "YYYY-MM-DD"
      )}&age=${formik.values.textInput}&role=${getRoleFromUrl()}`,
      {
        headers: {
          Authorization: `Bearer ${authToken}`,
        },
      }
    )
      .then((response) => response.json())
      .then((data) => {
        setData(data);
        setLoading(false);
        dispatch(LOADING_END());
      })
      .catch((error) => {
        console.error("Error fetching data:", error);
        setLoading(false);
        dispatch(LOADING_END());
      });
  };

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

  const dataSample = {
    labels: data.map((item) => formatJustDate(item.date)),
    datasets: [
      {
        label: "تعداد جوجه ریزی",
        data: data.map((item) => item.hatching_left_over),
        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 today = new Date();
  const defaultEndDate = addMonths(today, 1);

  const formik = useFormik({
    initialValues: {
      startDate: today,
      endDate: defaultEndDate,
      textInput: "45",
    },
    validationSchema: validationSchema,
    onSubmit: () => {
      fetchData();
    },
  });

  return (
    <Grid container direction="column">
      <Grid
        container
        justifyContent="center"
        alignItems="center"
        width="100%"
        className="header-stats"
        p={1}
      >
        <Typography>
          جوجه ریزی مانده در سالن براساس بازه زمانی و سن (تلفات پیش فرض 10٪)
        </Typography>
        <form onSubmit={formik.handleSubmit}>
          <Grid container direction="row" alignItems="center" gap={2}>
            <Grid>
              <DatePicker
                label="از تاریخ"
                value={formik.values.startDate}
                onChange={(date) => formik.setFieldValue("startDate", date)}
                renderInput={(params) => (
                  <TextField
                    {...params}
                    error={
                      formik.touched.startDate &&
                      Boolean(formik.errors.startDate)
                    }
                    helperText={
                      formik.touched.startDate && formik.errors.startDate
                    }
                  />
                )}
              />
            </Grid>
            <Grid>
              <DatePicker
                label="تا تاریخ"
                value={formik.values.endDate}
                onChange={(date) => formik.setFieldValue("endDate", date)}
                renderInput={(params) => (
                  <TextField
                    {...params}
                    error={
                      formik.touched.endDate && Boolean(formik.errors.endDate)
                    }
                    helperText={formik.touched.endDate && formik.errors.endDate}
                  />
                )}
              />
            </Grid>
            <Grid>
              <TextField
                name="textInput"
                label="سن"
                type="number"
                fullWidth
                margin="normal"
                value={formik.values.textInput}
                onChange={formik.handleChange}
                onBlur={formik.handleBlur}
                error={
                  formik.touched.textInput && Boolean(formik.errors.textInput)
                }
                helperText={formik.touched.textInput && formik.errors.textInput}
              />
            </Grid>
            <Grid>
              <Button
                type="submit"
                size="large"
                variant="contained"
                color="primary"
              >
                ارسال اطلاعات
              </Button>
            </Grid>
          </Grid>
        </form>
      </Grid>
      <Grid>
        {loading ? (
          <CircularProgress />
        ) : (
          <Bar
            style={{ direction: "ltr" }}
            data={dataSample}
            options={options}
          />
        )}
      </Grid>
    </Grid>
  );
};
