import React, { useContext } from "react";
import { useFormik } from "formik";
import * as yup from "yup";
import { TextField, Button } from "@mui/material";
import { Grid } from "../../../../components/grid/Grid";
import { useDispatch } from "react-redux";
import { AppContext } from "../../../../contexts/AppContext";
import { checkKillhouseRequestGuildService } from "../../services/check-killhouse-request-guild";
import { CLOSE_MODAL } from "../../../../lib/redux/slices/appSlice";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";

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

export const ProvinceManageGuildsSubmitRegisterCode = ({
  item,
  updateTable,
  userType,
}) => {
  const IS_STEWARD = userType === "steward";
  const dispatch = useDispatch();

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

  return (
    <Grid
      component="form"
      onSubmit={formik.handleSubmit}
      xs={12}
      justifyContent="center"
      alignItems="center"
    >
      <TextField
        fullWidth
        id="verificationCode"
        name="verificationCode"
        label="کد احراز"
        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"
        inputProps={{
          maxLength: 6,
          inputMode: "numeric",
          pattern: "[0-9]*",
        }}
        placeholder="کد احراز را وارد کنید"
      />

      <Button
        type="submit"
        variant="contained"
        color="primary"
        fullWidth
        sx={{ mt: 1 }}
      >
        ثبت کد
      </Button>
    </Grid>
  );
};
