import { Button, TextField } from "@mui/material";
import { useFormik } from "formik";
import { useContext } from "react";
import { useDispatch, useSelector } from "react-redux";
import { Grid } from "../../../../components/grid/Grid";
import { AppContext } from "../../../../contexts/AppContext";
import { SPACING } from "../../../../data/spacing";
import { CLOSE_MODAL } from "../../../../lib/redux/slices/appSlice";
import { Yup } from "../../../../lib/yup/yup";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { slaughterManageInventoryAllocationsService } from "../../services/salughter-manage-inventory-allocations";
import { slaughterAuthCodeSubmitService } from "../../services/slaughter-auth-code-submit";

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

export const SubmitAuthCode = ({ item }) => {
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);
  const [, , selectedDate1] = useContext(AppContext);

  const { inventorySelectedKillHouse } = useSelector(
    (state) => state.slaughterSlice
  );

  const formik = useFormik({
    initialValues: {
      phoneNumber: "",
    },
    validationSchema: validationSchema,
    onSubmit: (values) => {
      dispatch(
        slaughterAuthCodeSubmitService({
          logged_registration_code: values.phoneNumber,
          steward_allocation_key: item.key,
          role: getRoleFromUrl(),
        })
      ).then((r) => {
        dispatch(CLOSE_MODAL());
        if (r.payload.error) {
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: r.payload.error,
            severity: "error",
          });
        } else {
          dispatch(
            slaughterManageInventoryAllocationsService({
              kill_house_key: inventorySelectedKillHouse,
              date: selectedDate1,
            })
          );
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: "عملیات با موفقیت انجام شد.",
            severity: "success",
          });
        }
      });
    },
  });

  return (
    <form onSubmit={formik.handleSubmit}>
      <Grid container width="100%" direction="column" gap={SPACING.SMALL}>
        <TextField
          fullWidth
          id="phoneNumber"
          name="phoneNumber"
          label="کداحراز"
          variant="outlined"
          value={formik.values.phoneNumber}
          error={
            formik.touched.phoneNumber && Boolean(formik.errors.phoneNumber)
          }
          helperText={formik.touched.phoneNumber && formik.errors.phoneNumber}
          onChange={formik.handleChange}
          onBlur={formik.handleBlur}
        />
        <Button type="submit" fullWidth variant="contained">
          ثبت
        </Button>
      </Grid>
    </form>
  );
};
