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 {
  provincePolicyEditMarketDailyLimitation,
  provincePolicyGetMarketDailyLimitation,
} from "../../services/province-policy-market-daily-limitation";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";

export const ProvincePolicyMarketDailyLimitation = () => {
  const [isActive, setIsActive] = useState(false);
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);

  const formik = useFormik({
    initialValues: {
      quantity: "",
    },
    validationSchema: Yup.object({
      quantity: Yup.number()
        .required("این فیلد اجباری است")
        .min(1, "حداقل مقدار باید 1 باشد"),
    }),
  });

  const fetchData = () => {
    dispatch(provincePolicyGetMarketDailyLimitation()).then((r) => {
      if (r.payload?.data) {
        setIsActive(r.payload.data.active);
        formik.setFieldValue("quantity", r.payload.data.quantity);
      }
    });
  };

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

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

  const handleSubmit = (activeStatus) => {
    const registerRole = getRoleFromUrl();

    dispatch(
      provincePolicyEditMarketDailyLimitation({
        quantity: activeStatus ? parseInt(formik.values.quantity) : 0,
        active: activeStatus,
        register_role: registerRole,
      })
    ).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",
        });
      }
    });
  };

  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="marketDailyLimit"
              checked={isActive}
              onClick={() => {
                setIsActive(true);
              }}
            />
          }
          label="فعال"
        />
        <FormControlLabel
          control={
            <Radio
              checked={!isActive}
              onClick={() => {
                setIsActive(false);
                handleSubmit(false);
              }}
              name="marketDailyLimit"
            />
          }
          label="غیر فعال"
        />
      </Grid>
      {isActive && (
        <>
          <Grid>
            <TextField
              size="small"
              label="میزان محدودیت (براساس تعداد)"
              name="quantity"
              type="number"
              value={formik.values.quantity}
              onChange={formik.handleChange}
              error={formik.touched.quantity && Boolean(formik.errors.quantity)}
              helperText={formik.touched.quantity && formik.errors.quantity}
              required
            />
          </Grid>

          <Grid>
            <Button
              fullWidth
              disabled={!formik.isValid}
              variant="contained"
              onClick={() => handleSubmit(true)}
            >
              ثبت
            </Button>
          </Grid>
        </>
      )}
    </Grid>
  );
};
