import React, { useContext } from "react";
import { Grid, TextField, Button } from "@mui/material";
import { useDispatch } from "react-redux";
import { useFormik } from "formik";
import * as Yup from "yup";
import { CLOSE_MODAL } from "../../../../lib/redux/slices/appSlice";
import { SPACING } from "../../../../data/spacing";
import { slaughterEditFreeSaleService } from "../../../slaughter-house/services/slaughter-edit-free-sale";
import { AppContext } from "../../../../contexts/AppContext";

const validationSchema = Yup.object({
  weight: Yup.number().positive("عدد مثبت وارد کنید"),
  amount: Yup.number().positive("عدد مثبت وارد کنید"),
});

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

  const formik = useFormik({
    initialValues: {
      weight: "",
      amount: "",
    },
    validationSchema: validationSchema,
  });

  const submitData = (state) => {
    dispatch(
      slaughterEditFreeSaleService({
        key: item?.key,
        kill_house_vet_state: state,
        kill_house_vet_quantity: parseInt(formik.values.amount),
        kill_house_vet_weight: parseInt(formik.values.weight),
      })
    ).then((r) => {
      dispatch(CLOSE_MODAL());
      updateTable(1);
      if (r.payload.error) {
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: r.payload.error,
          severity: "error",
        });
      } else {
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: "عملیات با موفقیت انجام شد.",
          severity: "success",
        });
      }
    });
  };

  return (
    <Grid container gap={SPACING.SMALL} justifyContent="center">
      <TextField
        fullWidth
        id="amount"
        name="amount"
        label="حجم"
        value={formik.values.amount}
        onChange={formik.handleChange}
        error={formik.touched.amount && Boolean(formik.errors.amount)}
        helperText={formik.touched.amount && formik.errors.amount}
      />
      <TextField
        fullWidth
        id="weight"
        name="weight"
        label="وزن"
        value={formik.values.weight}
        onChange={formik.handleChange}
        error={formik.touched.weight && Boolean(formik.errors.weight)}
        helperText={formik.touched.weight && formik.errors.weight}
      />

      <Button
        variant="contained"
        disabled={!formik.isValid}
        onClick={() => {
          submitData("accepted");
        }}
      >
        تایید
      </Button>
      <Button
        color="error"
        variant="outlined"
        onClick={() => {
          submitData("rejected");
        }}
        disabled={!formik.isValid}
      >
        رد
      </Button>
    </Grid>
  );
};
