import React, { useContext } from "react";
import { TextField, Button } from "@mui/material";
import { Formik, Form, Field, ErrorMessage } from "formik";
import * as Yup from "yup";
import { useDispatch } from "react-redux";
import { archiveHatchingService } from "../../services/archive-hatching";
import { AppContext } from "../../../../contexts/AppContext";
import { CLOSE_MODAL } from "../../../../lib/redux/slices/appSlice";

const validationSchema = Yup.object().shape({
  looses_amount: Yup.number()
    .required("این فیلد اجباری است!")
    .min(0, "عدد مثبت وارد کنید!"),
});

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

  const handleSubmit = (values, { resetForm }) => {
    dispatch(
      archiveHatchingService({
        key: item?.key,
        direct_losses: values.looses_amount,
      })
    ).then((r) => {
      if (r.payload.error) {
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: r.payload.error,
          severity: "error",
        });
      } else {
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: "عملیات با موفقیت انجام شد.",
          severity: "success",
        });
        updateTable();
        dispatch(CLOSE_MODAL());
      }
    });
    resetForm();
  };

  return (
    <div>
      <Formik
        initialValues={{ looses_amount: "" }}
        validationSchema={validationSchema}
        onSubmit={handleSubmit}
      >
        {({ handleChange, handleBlur }) => (
          <Form>
            <Field
              as={TextField}
              name="looses_amount"
              label="حجم تلفات"
              type="number"
              onChange={handleChange}
              onBlur={handleBlur}
              fullWidth
              variant="outlined"
              margin="normal"
              helperText={<ErrorMessage name="looses_amount" />}
            />
            <Button type="submit" variant="contained" color="primary" fullWidth>
              ثبت
            </Button>
          </Form>
        )}
      </Formik>
    </div>
  );
};
