import { useContext } from "react";
import { useDispatch, useSelector } from "react-redux";
import { AppContext } from "../../../../contexts/AppContext";
import { Yup } from "../../../../lib/yup/yup";
import { useFormik } from "formik";
import { CLOSE_MODAL } from "../../../../lib/redux/slices/appSlice";
import { Grid } from "../../../../components/grid/Grid";
import { Button, TextField } from "@mui/material";
import { NumberInput } from "../../../../components/number-format-custom/NumberFormatCustom";
import moment from "moment";
import { DatePicker } from "@mui/x-date-pickers";
import { provinceDispenserStewardEditSaleOutService } from "../../services/province-dispenser-steward-edit-sale-out";
import { fetchSlaughterBroadcastAndProducts } from "../../../slaughter-house/services/handle-fetch-slaughter-products";

export const ProvinceStewardEditSaleOutOperation = ({
  editData,
  fetchData,
  fetchApiData,
  fetchDashboardData,
}) => {
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);
  const selectedSubUser = useSelector(
    (state) => state.userSlice.selectedSubUser
  );

  const validationSchema = Yup.object({
    weight: Yup.number().min(1, "یک مقدار مثبت وارد کنید!"),
    quarantineCode: Yup.string(),
    date: Yup.date(),
  });

  const formik = useFormik({
    initialValues: {
      weight: editData?.weightOfCarcasses || "",
      quarantineCode: editData?.clearanceCode || "",
      date: editData?.date ? moment(editData.date) : moment(),
    },
    validationSchema,
    enableReinitialize: true,
  });

  const successSubmit = () => {
    dispatch(CLOSE_MODAL());
    openNotif({
      vertical: "top",
      horizontal: "center",
      msg: "وزن با موفقیت ویرایش شد.",
      severity: "success",
    });
    dispatch(
      fetchSlaughterBroadcastAndProducts({
        role_key: selectedSubUser?.key || "",
      })
    );
    fetchApiData(1);
    fetchDashboardData();
  };

  return (
    <Grid
      container
      xs={12}
      direction="column"
      justifyContent="center"
      alignItems="center"
      gap={2}
    >
      <NumberInput
        allowLeadingZeros
        thousandSeparator=","
        fullWidth
        id="weight"
        label="وزن لاشه (کیلوگرم)"
        variant="outlined"
        value={formik.values.weight}
        error={formik.touched.weight && Boolean(formik.errors.weight)}
        onChange={formik.handleChange}
        onBlur={formik.handleBlur}
        helperText={
          formik.touched.weight && formik.errors.weight
            ? formik.errors.weight
            : null
        }
      />
      <TextField
        fullWidth
        id="quarantineCode"
        label="کد قرنطینه"
        variant="outlined"
        value={formik.values.quarantineCode}
        error={
          formik.touched.quarantineCode && Boolean(formik.errors.quarantineCode)
        }
        onChange={formik.handleChange}
        onBlur={formik.handleBlur}
        helperText={
          formik.touched.quarantineCode && formik.errors.quarantineCode
            ? formik.errors.quarantineCode
            : null
        }
      />

      <DatePicker
        label="تاریخ"
        id="date"
        value={formik.values.date}
        onChange={(value) => {
          formik.setFieldValue("date", value);
        }}
        onBlur={() => formik.setFieldTouched("date", true)}
        renderInput={(params) => (
          <TextField
            {...params}
            error={formik.touched.date && Boolean(formik.errors.date)}
            helperText={formik.touched.date && formik.errors.date}
            fullWidth
          />
        )}
      />

      <Button
        variant="contained"
        fullWidth
        disabled={!formik.isValid || formik.isSubmitting}
        onClick={() => {
          const req = {
            key: editData?.key,
            weight_of_carcasses: formik.values.weight,
            quarantineCode: formik.values.quarantineCode,
            date: moment(formik.values.date).format("YYYY-MM-DD HH:mm:ss"),
          };

          dispatch(provinceDispenserStewardEditSaleOutService(req)).then(
            (r) => {
              if (r.payload.error) {
                openNotif({
                  vertical: "top",
                  horizontal: "center",
                  msg: r.payload.error,
                  severity: "error",
                });
              } else {
                successSubmit();
                fetchData();
              }
            }
          );
        }}
      >
        ثبت
      </Button>
    </Grid>
  );
};
