import {
  Button,
  FormControl,
  FormHelperText,
  TextField,
  Typography,
} from "@mui/material";
import { useFormik } from "formik";
import { useContext } from "react";
import { useDispatch } 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 { archiveOldHatchingsService } from "../../services/archive-old-hatchings";

export const CityArchiveOldHatchings = () => {
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);
  const validationSchema = Yup.object().shape({
    numberField: Yup.number().typeError("عدد وارد کنید").required("اجباری است"),
  });

  const initialValues = {
    numberField: "",
  };

  const onSubmit = (values) => {
    dispatch(
      archiveOldHatchingsService({
        age: values.numberField,
        role: getRoleFromUrl(),
      })
    ).then((r) => {
      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: r.payload.data.msg,
          severity: "success",
        });
      }
    });
  };

  const formik = useFormik({
    initialValues,
    onSubmit,
    validationSchema,
  });

  return (
    <form onSubmit={formik.handleSubmit}>
      <Grid container gap={SPACING.TINY}>
        <Typography variant="caption" color="error">
          توجه : تمام جوجه ریزی های فعالی که بیشتر از سن وارده شده در کادر زیر
          باشند به بایگانی منتقل میشوند.
        </Typography>
        <FormControl
          fullWidth
          error={formik.touched.numberField && formik.errors.numberField}
        >
          <TextField
            name="numberField"
            label="بایگانی کردن جوجه ریزی ها از سن"
            type="number"
            value={formik.values.numberField}
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
          />
          {formik.touched.numberField && formik.errors.numberField && (
            <FormHelperText>{formik.errors.numberField}</FormHelperText>
          )}
        </FormControl>
        <Button type="submit" variant="contained" color="primary" fullWidth>
          ثبت
        </Button>
      </Grid>
    </form>
  );
};
