import { useContext, useEffect, useState } from "react";
import { useDispatch } from "react-redux";
import { AppContext } from "../../../../contexts/AppContext";
import { useFormik } from "formik";
import { Yup } from "../../../../lib/yup/yup";
import { Grid } from "../../../../components/grid/Grid";
import { Button, TextField, Typography } from "@mui/material";
import { provincePolicyGetDropLimitService } from "../../services/province-policy-drop-limit";
import { provinceEditDropLimitedService } from "../../services/province-policy-edit-drop-limited";

export const ProvincePolicyDropLimit = () => {
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);
  const [data, setData] = useState();

  useEffect(() => {
    dispatch(provincePolicyGetDropLimitService()).then((r) => {
      setData(r.payload.data);
    });
  }, []);

  const formik = useFormik({
    initialValues: {
      limitDown: "",
      limitUp: "",
    },
    validationSchema: Yup.object({
      limitDown: Yup.number()
        .required("این فیلد اجباری است")
        .min(0, "حداقل مقدار باید 0 باشد")
        .max(100, "حداکثر مقدار باید 100 باشد"),
      limitUp: Yup.number()
        .required("این فیلد اجباری است")
        .min(0, "حداقل مقدار باید 0 باشد")
        .max(100, "حداکثر مقدار باید 100 باشد"),
    }),
  });

  useEffect(() => {
    formik.validateForm();
  }, []);

  useEffect(() => {
    if (data?.killHouseLimitPercentDown) {
      formik.setFieldValue("limitDown", data?.killHouseLimitPercentDown);
      formik.setFieldValue("limitUp", data?.killHouseLimitPercentUp);
      formik.validateForm();
    }
  }, [data]);

  return (
    <Grid
      container
      xs={12}
      gap={2}
      alignItems="center"
      justifyContent="space-between"
      sx={{ width: "370px" }}
      isPolicy
    >
      <Typography variant="body1">حداقل و حداکثرافت برای کشتارگاه</Typography>

      <Grid container xs={12}>
        <Grid xs={6}>
          <TextField
            size="small"
            label="حداقل افت کشتار (درصد)"
            name="limitDown"
            value={formik.values.limitDown}
            onChange={formik.handleChange}
            error={formik.touched.limitDown && Boolean(formik.errors.limitDown)}
            helperText={formik.touched.limitDown && formik.errors.limitDown}
            required
            type="number"
            inputProps={{ min: 0, max: 100 }}
          />
        </Grid>

        <Grid xs={6}>
          <TextField
            size="small"
            label="حداکثر افت کشتار (درصد)"
            name="limitUp"
            value={formik.values.limitUp}
            onChange={formik.handleChange}
            error={formik.touched.limitUp && Boolean(formik.errors.limitUp)}
            helperText={formik.touched.limitUp && formik.errors.limitUp}
            required
            type="number"
            inputProps={{ min: 0, max: 100 }}
          />
        </Grid>
      </Grid>

      <Grid container xs={12} md={2}>
        <Button
          disabled={!formik.isValid}
          variant="contained"
          onClick={() => {
            dispatch(
              provinceEditDropLimitedService({
                active: true,
                kill_house_limit_percent_up: parseInt(formik.values.limitUp),
                kill_house_limit_percent_down: parseInt(
                  formik.values.limitDown
                ),
              })
            ).then((r) => {
              if (r.error) {
                openNotif({
                  vertical: "top",
                  horizontal: "center",
                  msg: "مشکلی پیش آمده است!",
                  severity: "error",
                });
              } else {
                openNotif({
                  vertical: "top",
                  horizontal: "center",
                  msg: "عملیات با موفقیت انجام شد.",
                  severity: "success",
                });
              }
            });
          }}
        >
          ارسال
        </Button>
      </Grid>
    </Grid>
  );
};
