import React, { useContext, useEffect } from "react";
import { Grid } from "../../../../components/grid/Grid";
import { Button, InputAdornment } from "@mui/material";
import { useDispatch, useSelector } from "react-redux";
import { NumberInput } from "../../../../components/number-format-custom/NumberFormatCustom";
import { useFormik } from "formik";
import { Yup } from "../../../../lib/yup/yup";
import {
  slaughterAllocateStewardService,
  slaughterEditAllocateStewardService,
} from "../../services/slaughter-allocate-steward";
import { AppContext } from "../../../../contexts/AppContext";
import { CLOSE_MODAL } from "../../../../lib/redux/slices/appSlice";
import { fetchSlaughterBroadcastAndProducts } from "../../services/handle-fetch-slaughter-products";
export const SlaughterHouseColdHouseBarsEdit = ({
  sellerType,
  fetchData,
  sellType,
  updateTable,
  fetchApiData,
  editData,
  isColdHouse,
  priceInfo,
}) => {
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);
  const selectedSubUser = useSelector(
    (state) => state.userSlice.selectedSubUser
  );

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

  const formik = useFormik({
    initialValues: {
      weight: editData?.realWeightOfCarcasses || "",
    },
    validationSchema,
  });

  useEffect(() => {
    formik.validateForm();
  }, []);

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

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

      <NumberInput
        disabled={priceInfo?.active}
        allowLeadingZeros
        thousandSeparator=","
        fullWidth
        id="price"
        label="قیمت هر کیلوگرم"
        variant="outlined"
        InputProps={{
          endAdornment: <InputAdornment position="start">ریال</InputAdornment>,
        }}
        value={formik.values.price}
        error={formik.touched.price ? Boolean(formik.errors.price) : null}
        onChange={formik.handleChange}
        onBlur={formik.handleBlur}
        helperText={
          formik.touched.price && Boolean(formik.errors.price)
            ? formik.errors.price
            : null
        }
      />

      <NumberInput
        disabled
        allowLeadingZeros
        thousandSeparator=","
        fullWidth
        id="wholePrice"
        label="هزینه کل"
        variant="outlined"
        InputProps={{
          endAdornment: <InputAdornment position="start">ریال</InputAdornment>,
        }}
        value={formik.values.wholePrice}
        error={
          formik.touched.wholePrice ? Boolean(formik.errors.wholePrice) : null
        }
        onChange={formik.handleChange}
        onBlur={formik.handleBlur}
        helperText={
          formik.touched.wholePrice && Boolean(formik.errors.wholePrice)
            ? formik.errors.wholePrice
            : null
        }
      />

      <Button
        variant="contained"
        fullWidth
        disabled={!formik.isValid}
        onClick={() => {
          let req = {};
          if (!editData) {
            req = {
              seller_type: sellerType,
              type: "manual",
              number_of_carcasses: 0,
              weight_of_carcasses: formik.values.weight,
              sell_type: sellType,
              buyer_type: "ColdHouse",
              allocation_type: "ColdHouse",
            };
          } else {
            req = {
              weight_of_carcasses: formik.values.weight,
              allocation_key: editData?.key,
            };
          }

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