import React, { useContext, useEffect, useState } from "react";
import { Grid } from "../../../../components/grid/Grid";
import {
  Button,
  FormControl,
  FormControlLabel,
  Radio,
  RadioGroup,
  TextField,
  Typography,
} from "@mui/material";
import { Yup } from "../../../../lib/yup/yup";
import { useFormik } from "formik";
import { useDispatch } from "react-redux";
import { AppContext } from "../../../../contexts/AppContext";
import { getMinMaxSlaughterAgeState } from "../../services/get-min-max-age-state";
import { provinceEditMinMaxAge } from "../../services/province-edit-min-max-age";

export const ProvincePolicySlaughterAge = () => {
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);

  const [value, setValue] = useState("inactive");
  const [data, setData] = useState();

  useEffect(() => {
    dispatch(getMinMaxSlaughterAgeState()).then((r) => {
      setData(r.payload.data);
      if (r.payload.data?.active) {
        setValue("active");
      }
    });
  }, []);

  const formik = useFormik({
    initialValues: {
      minAge: "",
      maxAge: "",
    },
    validationSchema: Yup.object({
      minAge: Yup.number().required("این فیلد اجباری است"),
      maxAge: Yup.number().required("این فیلد اجباری است"),
    }),
  });

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

  useEffect(() => {
    if (data?.minimum) {
      formik.setFieldValue("minAge", data?.minimum);
      formik.setFieldValue("maxAge", data?.maximum);
      formik.validateForm();
    }
  }, [data]);

  const handleChangeRadioButton = (event) => {
    setValue(event.target.value);
  };

  return (
    <Grid
      container
      xs={12}
      gap={2}
      alignItems="center"
      justifyContent="space-between"
      isPolicy
      sx={{
        width: {
          xs: "100%",
          sm: "48%",
          lg: "24%",
          nxl: "19%",
        },
      }}
    >
      <Typography variant="body1">حداقل و حداکثر سن کشتار</Typography>
      <FormControl>
        <RadioGroup
          aria-labelledby="demo-controlled-radio-buttons-group"
          name="controlled-radio-buttons-group"
          value={value}
          onChange={handleChangeRadioButton}
          row
        >
          <FormControlLabel value="active" control={<Radio />} label="فعال" />
          <FormControlLabel
            onClick={() => {
              dispatch(
                provinceEditMinMaxAge({
                  active: false,
                })
              ).then((r) => {
                if (r.error) {
                  openNotif({
                    vertical: "top",
                    horizontal: "center",
                    msg: "مشکلی پیش آمده است!",
                    severity: "error",
                  });
                } else {
                  openNotif({
                    vertical: "top",
                    horizontal: "center",
                    msg: "عملیات با موفقیت انجام شد.",
                    severity: "success",
                  });
                }
              });
            }}
            value="inactive"
            control={<Radio />}
            label="غیر فعال"
          />
        </RadioGroup>
      </FormControl>
      {value === "active" && (
        <>
          <Grid container xs={12}>
            <Grid xs={6}>
              <TextField
                size="small"
                label="حداقل سن کشتار"
                name="minAge"
                value={formik.values.minAge}
                onChange={formik.handleChange}
                error={formik.touched.minAge && Boolean(formik.errors.minAge)}
                helperText={formik.touched.minAge && formik.errors.minAge}
                required
              />
            </Grid>

            <Grid xs={6}>
              <TextField
                size="small"
                label="حداکثر سن کشتار"
                name="maxAge"
                value={formik.values.maxAge}
                onChange={formik.handleChange}
                error={formik.touched.maxAge && Boolean(formik.errors.maxAge)}
                helperText={formik.touched.maxAge && formik.errors.maxAge}
                required
              />
            </Grid>
          </Grid>
          <Grid container xs={12} md={2}>
            <Button
              disabled={!formik.isValid}
              variant="contained"
              onClick={() => {
                dispatch(
                  provinceEditMinMaxAge({
                    active: true,
                    maximum: parseInt(formik.values.maxAge),
                    minimum: parseInt(formik.values.minAge),
                  })
                ).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>
  );
};
