import { Button, IconButton, Popover } from "@mui/material";
import { useState } from "react";
import { useDispatch } from "react-redux";
import TuneIcon from "@mui/icons-material/Tune";
import { stewardDeleteFreeBarService } from "../../../guild/services/steward-submit-free-bar-service";
import { Grid } from "../../../../components/grid/Grid";
import { DRAWER } from "../../../../lib/redux/slices/appSlice";
import { StewardSubmitFreeBar } from "../steward-submit-free-bar/StewardSubmitFreeBar";

export const StewardSellOutOperations = ({ item, updateTable }) => {
  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 handleDelete = () => {
    handleClose();
    dispatch(stewardDeleteFreeBarService(item.key)).then(() => {
      updateTable();
    });
  };

  return (
    <div>
      <IconButton
        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" gap={1}>
            <Button
              onClick={() => {
                handleClose();
                dispatch(
                  DRAWER({
                    right: !(window.innerWidth <= 600),
                    bottom: window.innerWidth <= 600,
                    title: "ویرایش خرید خارج استان",
                    content: (
                      <StewardSubmitFreeBar
                        item={item}
                        updateTable={updateTable}
                      />
                    ),
                  })
                );
              }}
            >
              ویرایش
            </Button>
            <Button color="error" onClick={handleDelete}>
              حذف
            </Button>
          </Grid>
        </div>
      </Popover>
    </div>
  );
};
