import { Button, TextField, Typography } from "@mui/material";
import { useContext, useState } 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 { provinceAcceptSlaughterFreeBuyService } from "../../../slaughter-house/services/province-accept-slaughter-free-buy";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";

export const ProvinceAcceptDirectBuy = ({ item, updateTable }) => {
  const [openNotif] = useContext(AppContext);
  const dispatch = useDispatch();
  const [text, setText] = useState(item.killCapacity);

  const handleTextChange = (event) => {
    setText(event.target.value);
  };

  return (
    <Grid container direction="column" gap={SPACING.TINY} width="100%">
      <Typography variant="body1" color="error">
        مانده در سالن مرغدار:{"‌ "}
        {item?.poultry?.leftOverOwnHatching?.toLocaleString()}
      </Typography>
      <TextField
        label="تعداد تایید شده"
        variant="outlined"
        type="number"
        fullWidth
        value={text}
        onChange={handleTextChange}
      />

      <Button
        variant="contained"
        disabled={parseInt(text) > item?.poultry?.leftOverOwnHatching || !text}
        fullWidth
        onClick={() => {
          dispatch(
            provinceAcceptSlaughterFreeBuyService({
              state: "accepted",
              kill_request_key: item.key,
              quantity: text,
              role: getRoleFromUrl(),
            })
          ).then((r) => {
            if (r.payload.error) {
              openNotif({
                vertical: "top",
                horizontal: "center",
                msg: r.payload.error,
                severity: "error",
              });
            } else {
              updateTable();
              openNotif({
                vertical: "top",
                horizontal: "center",
                msg: "عملیات با موفقیت انجام شد.",
                severity: "success",
              });
              dispatch(CLOSE_MODAL());
            }
          });
        }}
      >
        ثبت
      </Button>
    </Grid>
  );
};
