import React, { useContext } from "react";
import { useFormik } from "formik";
import { Yup } from "../../../../lib/yup/yup";
import { Button, TextField } from "@mui/material";
import { useDispatch } from "react-redux";
import { slaughterEditFreeBuyService } from "../../services/slaughter-edit-free-buy";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { AppContext } from "../../../../contexts/AppContext";
import { CLOSE_MODAL } from "../../../../lib/redux/slices/appSlice";
import { Grid } from "../../../../components/grid/Grid";
import { SPACING } from "../../../../data/spacing";

export const EnterAuthCodeDirectBuy = ({ item, updateTable }) => {
  const [openNotif] = useContext(AppContext);
  const dispatch = useDispatch();
  const formik = useFormik({
    initialValues: {
      textFieldValue: "", // Initial value for your text field
    },
    validationSchema: Yup.object({
      textFieldValue: Yup.string().required("این فیلد الزامی است"), // Validation schema for the text field
    }),
    onSubmit: (values) => {
      dispatch(
        slaughterEditFreeBuyService({
          role: getRoleFromUrl(),
          kill_request_key: item.key,
          input_direct_buying_code: values.textFieldValue,
        })
      ).then((r) => {
        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());
        }
      });
    },
  });

  return (
    <form onSubmit={formik.handleSubmit}>
      <Grid container gap={SPACING.TINY}>
        <TextField
          fullWidth
          id="textFieldValue"
          name="textFieldValue"
          label="کداحراز"
          variant="outlined"
          onChange={formik.handleChange}
          onBlur={formik.handleBlur}
          value={formik.values.textFieldValue}
          error={
            formik.touched.textFieldValue &&
            Boolean(formik.errors.textFieldValue)
          }
          helperText={
            formik.touched.textFieldValue && formik.errors.textFieldValue
          }
        />

        <Button fullWidth type="submit" variant="contained" color="primary">
          ثبت
        </Button>
      </Grid>
    </form>
  );
};
