import { Button, IconButton, Popover } from "@mui/material";
import { useState } from "react";
import { useDispatch } from "react-redux";
import { Grid } from "../../../../components/grid/Grid";
import { DRAWER, OPEN_MODAL } from "../../../../lib/redux/slices/appSlice";
import { slaughterDeleteInventoryFreeBarService } from "../../services/slaughter-delete-inventory-free-bar";
import { SlaughterSubmitFreeBar } from "../slaughter-submit-free-bar/SlaughterSubmitFreeBar";
import { SlaughterSubmitRealInventoryFreeBar } from "../slaughter-submit-real-inventory-free-bar/SLaughterSubmitRealInverntoryFreeBar";
import TuneIcon from "@mui/icons-material/Tune";
import { fetchSlaughterBroadcastAndProducts } from "../../services/handle-fetch-slaughter-products";

export const SlaughterFreeBarsAlivesOperations = ({
  item,
  updateTable,
  barState,
  type,
}) => {
  const dispatch = useDispatch();

  const [anchorEl, setAnchorEl] = useState(null);

  const handleClick = (event) => {
    setAnchorEl(event.currentTarget);
  };

  const handleClose = () => {
    setAnchorEl(null);
  };

  const open = Boolean(anchorEl);
  const id = open ? "popover" : undefined;

  const ableToSeeDelete = () => {
    if (type === "carcass" || item?.buyType !== "live") {
      return true;
    } else {
      if (!barState && !item.weightOfCarcasses) {
        return true;
      } else {
        return false;
      }
    }
  };

  const isAbleToSee =
    item?.registerType === "automatic"
      ? false
      : item.weightOfCarcasses && !barState && item?.buyType === "live";

  return (
    <div>
      <IconButton
        disabled={isAbleToSee}
        aria-describedby={id}
        variant="contained"
        color="primary"
        onClick={handleClick}
      >
        <TuneIcon />
      </IconButton>
      <Popover
        anchorOrigin={{
          vertical: "bottom",
          horizontal: "right",
        }}
        transformOrigin={{
          vertical: "top",
          horizontal: "left",
        }}
        id={id}
        open={open}
        anchorEl={anchorEl}
        onClose={handleClose}
      >
        <div style={{ padding: "20px" }}>
          <Grid container direction="column">
            {barState === "entered" && item?.registerType === "automatic" && (
              <Button
                onClick={() => {
                  handleClose();
                  dispatch(
                    DRAWER({
                      right: !(window.innerWidth <= 600),
                      bottom: window.innerWidth <= 600,
                      title: "ویرایش بار آزاد",
                      content: (
                        <SlaughterSubmitFreeBar
                          item={item}
                          updateTable={updateTable}
                        />
                      ),
                    })
                  );
                }}
              >
                ویرایش
              </Button>
            )}
            {(barState === "entered"
              ? item?.registerType !== "automatic"
              : true) && (
              <Button
                onClick={() => {
                  handleClose();
                  dispatch(
                    OPEN_MODAL({
                      title: "ثبت اطلاعات لاشه ورودی به انبار",
                      content: (
                        <SlaughterSubmitRealInventoryFreeBar
                          item={item}
                          updateTable={updateTable}
                          IsEdit={barState === "entered"}
                        />
                      ),
                    })
                  );
                }}
              >
                {barState === "entered" ? "ویرایش" : "ورود به انبار"}
              </Button>
            )}

            {ableToSeeDelete() && item?.registerType !== "automatic" && (
              <Button
                color="error"
                onClick={() => {
                  handleClose();
                  dispatch(
                    slaughterDeleteInventoryFreeBarService(item.key)
                  ).then(() => {
                    updateTable();
                    dispatch(fetchSlaughterBroadcastAndProducts());
                  });
                }}
              >
                حذف
              </Button>
            )}
          </Grid>
        </div>
      </Popover>
    </div>
  );
};
