import React, { useContext, useEffect, useState } from "react";
import { Grid } from "../../../../components/grid/Grid";
import {
  Button,
  FormControlLabel,
  Radio,
  TextField,
  Typography,
} from "@mui/material";
import { useFormik } from "formik";
import { useDispatch } from "react-redux";
import { Yup } from "../../../../lib/yup/yup";
import { AppContext } from "../../../../contexts/AppContext";
import {
  provincePolicyEditAggregateBarInfoAllowStatus,
  provincePolicyGetAggregateBarInfoAllowStatus,
} from "../../services/province-policy-get-aggregate-bar-info-allow-state";

export const ProvincePolicyCouncilAllowAggegateBarInfo = () => {
  const [aggregateStatus, setAggregateStatus] = useState(false);
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);

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

  const fetchData = () => {
    dispatch(provincePolicyGetAggregateBarInfoAllowStatus()).then((r) => {
      setAggregateStatus(r.payload.data.allow);
      formik.setFieldValue("maxLimit", r.payload.data.limitation);
    });
  };

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

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

  return (
    <Grid
      container
      alignItems="center"
      gap={2}
      justifyContent="space-between"
      isPolicy
      sx={{
        width: {
          xs: "100%",
          sm: "48%",
          lg: "24%",
          nxl: "19%",
        },
      }}
    >
      <Grid>
        <Typography variant="body1">مجوز ادغام بار (کد قرنطینه) </Typography>
      </Grid>
      <Grid container xs={12} justifyContent="space-between">
        <FormControlLabel
          control={
            <Radio
              name="item6"
              checked={aggregateStatus}
              onClick={() => {
                setAggregateStatus(true);
              }}
            />
          }
          label="فعال"
        />
        <FormControlLabel
          control={
            <Radio
              checked={!aggregateStatus}
              onClick={() => {
                dispatch(
                  provincePolicyEditAggregateBarInfoAllowStatus({
                    allow: false,
                  })
                ).then((r) => {
                  if (r.payload.error) {
                    openNotif({
                      vertical: "top",
                      horizontal: "center",
                      msg: r.payload.error,
                      severity: "error",
                    });
                  } else {
                    fetchData();
                    openNotif({
                      vertical: "top",
                      horizontal: "center",
                      msg: "عملیات با موفقیت انجام شد.",
                      severity: "success",
                    });
                  }
                });
              }}
              name="item6"
            />
          }
          label="غیر فعال"
        />
      </Grid>
      {aggregateStatus && (
        <>
          <Grid>
            <TextField
              size="small"
              label="میزان محدودیت (براساس تعداد)"
              name="maxLimit"
              value={formik.values.maxLimit}
              onChange={formik.handleChange}
              error={formik.touched.maxLimit && Boolean(formik.errors.maxLimit)}
              helperText={formik.touched.maxLimit && formik.errors.maxLimit}
              required
            />
          </Grid>

          <Grid>
            <Button
              disabled={!formik.isValid}
              variant="contained"
              onClick={() => {
                dispatch(
                  provincePolicyEditAggregateBarInfoAllowStatus({
                    allow: true,
                    limitation: formik.values.maxLimit,
                  })
                ).then((r) => {
                  if (r.payload.error) {
                    openNotif({
                      vertical: "top",
                      horizontal: "center",
                      msg: r.payload.error,
                      severity: "error",
                    });
                  } else {
                    fetchData();
                    openNotif({
                      vertical: "top",
                      horizontal: "center",
                      msg: "عملیات با موفقیت انجام شد.",
                      severity: "success",
                    });
                  }
                });
              }}
            >
              ثبت
            </Button>
          </Grid>
        </>
      )}
    </Grid>
  );
};
