import React, { useContext } from "react";
import { useFormik } from "formik";
import { Button, TextField } from "@mui/material";
import { useDispatch } from "react-redux";
import { AppContext } from "../../../../contexts/AppContext";
import { archiveHatchingService } from "../../services/archive-hatching";
import { DRAWER } from "../../../../lib/redux/slices/appSlice";
import * as Yup from "yup";
// import { cityGetHatchingsByAge } from "../../services/city-get-hatchings-by-age";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { cityGetHatchingsByAge } from "../../services/city-get-hatchings-by-age";

const validationSchema = Yup.object({
  name: Yup.string(),
});

export const CityArchiveHatchingDrawer = ({
  item,
  selectedAge1,
  selectedAge2,
  updateTable,
}) => {
  const [openNotif] = useContext(AppContext);

  const dispatch = useDispatch();

  const formik = useFormik({
    initialValues: {
      name: "",
    },
    validationSchema,
    onSubmit: (values) => {
      dispatch(
        archiveHatchingService({
          key: item.key,
          archive_state: "",
          message: values.name,
          role: getRoleFromUrl(),
        })
      ).then((r) => {
        if (r.payload.error) {
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: r.payload.error,
            severity: "error",
          });
        } else {
          dispatch(DRAWER({ right: false, bottom: false, content: null }));
          if (selectedAge1) {
            dispatch(cityGetHatchingsByAge({ selectedAge1, selectedAge2 }));
          }
          updateTable();
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: "عملیات با موفقیت انجام شد.",
            severity: "success",
          });
        }
      });
    },
  });

  return (
    <form onSubmit={formik.handleSubmit}>
      <TextField
        id="name"
        name="name"
        label="توضیحات"
        variant="outlined"
        multiline
        rows={4}
        fullWidth
        margin="normal"
        value={formik.values.name}
        onChange={formik.handleChange}
        onBlur={formik.handleBlur}
        helperText={formik.touched.name && formik.errors.name}
        error={formik.touched.name && Boolean(formik.errors.name)}
      />
      <Button type="submit" variant="contained" color="primary" fullWidth>
        ثبت
      </Button>
    </form>
  );
};
