import React, { useContext } from "react";
import { Grid } from "../../../../components/grid/Grid";
import { Button, TextField } from "@mui/material";
import { useFormik } from "formik";
import * as yup from "yup";
import { useDispatch } from "react-redux";
import { AppContext } from "../../../../contexts/AppContext";
import { guildAllocatedStockOperationService } from "../../../guild/services/guild-allocated-stock-operation";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";

const validationSchema = yup.object({
  verificationCode: yup
    .string()
    .required("کد احراز الزامی است")
    .matches(/^\d+$/, "کد احراز باید فقط شامل اعداد باشد"),
});

export const SlaughterSellCarcassInProvinceSubmitRegistrationCode = ({
  item,
  fetchApiData,
}) => {
  const dispatch = useDispatch();

  const [openNotif] = useContext(AppContext);
  const formik = useFormik({
    initialValues: {
      verificationCode: "",
    },
    validationSchema: validationSchema,
    onSubmit: (values) => {
      dispatch(
        guildAllocatedStockOperationService({
          steward_allocation_key: item?.key,
          logged_registration_code: values.verificationCode,
          role: getRoleFromUrl(),
        })
      ).then((r) => {
        if (r.payload.error) {
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: r.payload.error,
            severity: "error",
          });
        } else {
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: "عملیات با موفقیت انجام شد.",
            severity: "success",
          });
          fetchApiData();
        }
      });
    },
  });

  return (
    <Grid
      container
      xs={12}
      justifyContent="center"
      alignItems="center"
      direction="column"
    >
      <form onSubmit={formik.handleSubmit} style={{ width: "100%" }}>
        <Grid container xs={12} direction="column">
          <TextField
            sx={{ minWidth: "120px" }}
            size="small"
            fullWidth
            id="verificationCode"
            name="verificationCode"
            label="کد احراز"
            inputMode="numeric"
            value={formik.values.verificationCode}
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
            error={
              formik.touched.verificationCode &&
              Boolean(formik.errors.verificationCode)
            }
            helperText={
              formik.touched.verificationCode && formik.errors.verificationCode
            }
            variant="outlined"
          />

          <Button
            size="small"
            type="submit"
            color="primary"
            disabled={!formik.isValid}
          >
            ارسال
          </Button>
        </Grid>
      </form>
    </Grid>
  );
};
