import React, { useContext, useEffect } from "react";
import { Grid, TextField, Button } from "@mui/material";
import { useFormik } from "formik";
import * as yup from "yup";
import { useDispatch } from "react-redux";
import { provincePoultryRequestEnterConfirmationCodeService } from "../../services/province-poultry-request-enter-confirmation-code";
import { AppContext } from "../../../../contexts/AppContext";
import { CLOSE_MODAL } from "../../../../lib/redux/slices/appSlice";

export const ProvincePoultryRequestEnterConfirmationCode = ({
  updateTable,
  item,
}) => {
  const [openNotif] = useContext(AppContext);
  const dispatch = useDispatch();
  const validationSchema = yup.object({
    verificationCode: yup
      .string()
      .required("کد احراز الزامی است")
      .matches(/^\d+$/, "کد احراز باید عددی باشد")
      .length(5, "کد احراز باید 5 رقم باشد"),
  });

  const formik = useFormik({
    initialValues: {
      verificationCode: "",
    },
    validationSchema: validationSchema,
    onSubmit: (values) => {
      dispatch(
        provincePoultryRequestEnterConfirmationCodeService({
          poultry_request_key: item?.key,
          confirmation_code: values?.verificationCode,
        })
      ).then((r) => {
        updateTable();
        if (r.payload.error) {
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: r.payload.error,
            severity: "error",
          });
        } else {
          updateTable();
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: "عملیات با موفقیت انجام شد.",
            severity: "success",
          });
          dispatch(CLOSE_MODAL());
        }
      });
    },
  });

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

  return (
    <Grid container xs={12} justifyContent="center">
      <Grid item xs={12} mb={3}>
        <TextField
          fullWidth
          id="verificationCode"
          name="verificationCode"
          label="کد احراز"
          variant="outlined"
          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
          }
          inputProps={{
            maxLength: 6,
            inputMode: "numeric",
          }}
        />
      </Grid>
      <Grid item xs={12}>
        <Button
          fullWidth
          color="primary"
          variant="contained"
          onClick={formik.handleSubmit}
          type="submit"
          disabled={!formik.isValid || formik.isSubmitting}
          size="large"
        >
          تایید
        </Button>
      </Grid>
    </Grid>
  );
};
