import { DatePicker } from "@mui/x-date-pickers";
import { Button, TextField } from "@mui/material";
import { useFormik } from "formik";
import moment from "moment";
import { Grid } from "../../../../components/grid/Grid";
import { SPACING } from "../../../../data/spacing";
import { useDispatch } from "react-redux";
import { provinceEditSendDate } from "../../services/province-edit-send-date";
import { CLOSE_MODAL } from "../../../../lib/redux/slices/appSlice";
import { AppContext } from "../../../../contexts/AppContext";
import { useContext } from "react";
import { provinceGetAllRequests } from "../../services/province-get-all-requests";

export const ProvinceEditSendDate = ({ poultryRequestKey }) => {
  const [openNotif] = useContext(AppContext);
  const dispatch = useDispatch();
  const formik = useFormik({
    initialValues: {
      date: moment(Date()).format("YYYY-MM-DD hh:mm:ss"),
    },
  });

  return (
    <Grid container direction="column" gap={SPACING.SMALL}>
      <DatePicker
        fullWidth
        label="تاریخ"
        id="date"
        renderInput={(params) => <TextField {...params} />}
        value={formik.values.date}
        error={formik.touched.date ? Boolean(formik.errors.date) : null}
        onChange={(e) => {
          formik.setFieldValue("date", moment(e).format("YYYY-MM-DD hh:mm:ss"));
        }}
        onBlur={formik.handleBlur}
        helperText={
          formik.touched.date && Boolean(formik.errors.date)
            ? formik.errors.date
            : null
        }
      />
      <Button
        variant="contained"
        fullWidth
        onClick={() => {
          dispatch(
            provinceEditSendDate({
              key: poultryRequestKey,
              send_date: formik.values.date,
            })
          ).then((r) => {
            dispatch(provinceGetAllRequests());
            dispatch(CLOSE_MODAL());
            if (r.payload.error) {
              openNotif({
                vertical: "top",
                horizontal: "center",
                msg: r.payload.error,
                severity: "error",
              });
            } else {
              openNotif({
                vertical: "top",
                horizontal: "center",
                msg: "عملیات با موفقیت انجام شد.",
                severity: "success",
              });
            }
          });
        }}
      >
        ثبت
      </Button>
    </Grid>
  );
};
