import {
  IconButton,
  Popover,
  List,
  ListItem,
  ListItemButton,
  Typography,
  ListItemIcon,
} from "@mui/material";
import { useState } from "react";
import { useDispatch, useSelector } from "react-redux";
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";
import EditOutlinedIcon from "@mui/icons-material/EditOutlined";
import Inventory2OutlinedIcon from "@mui/icons-material/Inventory2Outlined";
import DeleteOutlineOutlinedIcon from "@mui/icons-material/DeleteOutlineOutlined";

export const SlaughterFreeBarsOperations = ({
  item,
  updateTable,
  barState,
  type,
}) => {
  const dispatch = useDispatch();
  const selectedSubUser = useSelector(
    (state) => state.userSlice.selectedSubUser
  );
  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 ableToSeeUpdate = () => {
    if (item?.buyType === "live") {
      return !item.weightOfCarcasses && !barState;
    } else {
      return false;
    }
  };
  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}
      >
        <List sx={{ p: 1 }}>
          {(ableToSeeUpdate() || item?.registerType === "automatic") && (
            <ListItem disablePadding>
              <ListItemButton
                sx={{ color: "primary.main" }}
                onClick={() => {
                  handleClose();
                  dispatch(
                    DRAWER({
                      right: !(window.innerWidth <= 600),
                      bottom: window.innerWidth <= 600,
                      title: "ویرایش بار آزاد",
                      content: (
                        <SlaughterSubmitFreeBar
                          item={item}
                          updateTable={updateTable}
                        />
                      ),
                    })
                  );
                }}
              >
                <ListItemIcon sx={{ minWidth: 36, color: "inherit" }}>
                  <EditOutlinedIcon fontSize="small" />
                </ListItemIcon>
                <Typography variant="body2">ویرایش</Typography>
              </ListItemButton>
            </ListItem>
          )}
          {barState && item?.registerType === "manual" && (
            <ListItem disablePadding>
              <ListItemButton
                sx={{ color: "success.main" }}
                onClick={() => {
                  handleClose();
                  dispatch(
                    OPEN_MODAL({
                      title: "ثبت اطلاعات لاشه ورودی به انبار",
                      content: (
                        <SlaughterSubmitRealInventoryFreeBar
                          item={item}
                          updateTable={updateTable}
                          IsEdit={barState === "entered"}
                        />
                      ),
                    })
                  );
                }}
              >
                <ListItemIcon sx={{ minWidth: 36, color: "inherit" }}>
                  <Inventory2OutlinedIcon fontSize="small" />
                </ListItemIcon>
                <Typography variant="body2">
                  {barState === "entered" ? "ویرایش" : "ورود به انبار"}
                </Typography>
              </ListItemButton>
            </ListItem>
          )}

          {ableToSeeDelete() && item?.registerType !== "automatic" && (
            <ListItem disablePadding>
              <ListItemButton
                sx={{ color: "error.main" }}
                onClick={() => {
                  handleClose();
                  dispatch(
                    slaughterDeleteInventoryFreeBarService(item.key)
                  ).then(() => {
                    updateTable();
                    dispatch(
                      fetchSlaughterBroadcastAndProducts({
                        role_key: selectedSubUser?.key || "",
                      })
                    );
                  });
                }}
              >
                <ListItemIcon sx={{ minWidth: 36, color: "inherit" }}>
                  <DeleteOutlineOutlinedIcon fontSize="small" />
                </ListItemIcon>
                <Typography variant="body2" color="inherit">
                  حذف
                </Typography>
              </ListItemButton>
            </ListItem>
          )}
        </List>
      </Popover>
    </div>
  );
};
