import {
  Button,
  IconButton,
  Popover,
  Tooltip,
  Typography,
} from "@mui/material";
import { useContext, useState } from "react";
import TuneIcon from "@mui/icons-material/Tune";
import { Grid } from "../../../../components/grid/Grid";
import { SPACING } from "../../../../data/spacing";
import { useDispatch } from "react-redux";
import { provinceAllocatedDeleteService } from "../../services/province-allocated-delete";
import { AppContext } from "../../../../contexts/AppContext";
import { provinceGetAllocatedRequestsService } from "../../services/province-get-allocated-requests";
import { provinceAllocatedReturnQuantityService } from "../../services/province-allocated-return-quantity";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { OPEN_MODAL } from "../../../../lib/redux/slices/appSlice";
import { ProvinceAllocatedRequestsEditAllocation } from "../province-allocated-requests-edit-allocation/ProvinceAllocatedRequestsEditAllocation";
import KeyboardReturnIcon from "@mui/icons-material/KeyboardReturn";
import DeleteIcon from "@mui/icons-material/Delete";
import EditIcon from "@mui/icons-material/Edit";
export const ProvinceAllocatedRequestsOperations = ({
  item,
  fetchDashboard,
}) => {
  const [anchorEl, setAnchorEl] = useState(null);
  const dispatch = useDispatch();

  const [openNotif, , selectedDate1, , selectedDate2] = useContext(AppContext);
  const handleClick = (event) => {
    setAnchorEl(event.currentTarget);
  };

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

  const open = Boolean(anchorEl);
  const id = open ? "simple-popover" : undefined;
  const btnDisabled =
    item.allocatedState === "rejected" ||
    (item.allocatedCarState && item.allocatedRemainQuantity === 0);

  return (
    <div>
      <IconButton
        aria-describedby={id}
        variant="contained"
        color="primary"
        disabled={btnDisabled}
        onClick={handleClick}
      >
        <TuneIcon />
      </IconButton>
      <Popover
        id={id}
        open={open}
        anchorEl={anchorEl}
        onClose={handleClose}
        anchorOrigin={{
          vertical: "bottom",
          horizontal: "right",
        }}
        transformOrigin={{
          vertical: "top",
          horizontal: "left",
        }}
      >
        <div style={{ padding: 10 }}>
          <Grid
            container
            direction="column"
            gap={SPACING.TINY}
            alignItems="flex-start"
            style={{ width: 180 }}
          >
            {getRoleFromUrl() !== "KillHouse" && (
              <Tooltip placement="left" title="ویرایش">
                <Button
                  size="small"
                  disabled={item?.directBuying}
                  startIcon={<EditIcon fontSize="small" />}
                  sx={{
                    "&.Mui-disabled": {
                      backgroundColor: "transparent",
                      color: "text.disabled",
                    },
                  }}
                  onClick={() => {
                    handleClose();
                    dispatch(
                      OPEN_MODAL({
                        title: "ویرایش تخصیص",
                        content: (
                          <ProvinceAllocatedRequestsEditAllocation
                            item={item}
                            selectedDate1={selectedDate1}
                            selectedDate2={selectedDate2}
                            fetchDashboard={fetchDashboard}
                          />
                        ),
                      })
                    );
                  }}
                >
                  <Typography variant="body2" textAlign="left" fontWeight={600}>
                    ویرایش تخصیص
                  </Typography>
                </Button>
              </Tooltip>
            )}

            {getRoleFromUrl() !== "KillHouse" && (
              <Tooltip placement="left" title="تخصیص مانده برگشت">
                <Button
                  size="small"
                  startIcon={<KeyboardReturnIcon fontSize="small" />}
                  sx={{
                    "&.Mui-disabled": {
                      backgroundColor: "transparent",
                      color: "text.disabled",
                    },
                  }}
                  onClick={() => {
                    dispatch(
                      provinceAllocatedReturnQuantityService({
                        province_kill_request_key: item.provinceKillRequestKey,
                      })
                    ).then((r) => {
                      if (r.payload.error) {
                        openNotif({
                          vertical: "top",
                          horizontal: "center",
                          msg: r.payload.error,
                          severity: "error",
                        });
                      } else {
                        handleClose();
                        dispatch(
                          provinceGetAllocatedRequestsService({
                            selectedDate1,
                            selectedDate2,
                          })
                        );
                        openNotif({
                          vertical: "top",
                          horizontal: "center",
                          msg: "عملیات با موفقیت انجام شد.",
                          severity: "success",
                        });
                      }
                    });
                  }}
                >
                  <Typography variant="body2" textAlign="left" fontWeight={600}>
                    تخصیص مانده برگشت
                  </Typography>
                </Button>
              </Tooltip>
            )}

            <Tooltip placement="left" title="حذف">
              <Button
                size="small"
                disabled={
                  getRoleFromUrl() !== "AdminX" && item.allocatedCarState
                }
                color="error"
                startIcon={<DeleteIcon fontSize="small" />}
                sx={{
                  "&.Mui-disabled": {
                    backgroundColor: "transparent",
                    color: "text.disabled",
                  },
                }}
                onClick={() => {
                  dispatch(
                    provinceAllocatedDeleteService({
                      province_kill_request_key: item.provinceKillRequestKey,
                    })
                  ).then((r) => {
                    if (r.payload.error) {
                      openNotif({
                        vertical: "top",
                        horizontal: "center",
                        msg: r.payload.error,
                        severity: "error",
                      });
                    } else {
                      handleClose();
                      dispatch(
                        provinceGetAllocatedRequestsService({
                          selectedDate1,
                          selectedDate2,
                        })
                      );
                      openNotif({
                        vertical: "top",
                        horizontal: "center",
                        msg: "عملیات با موفقیت انجام شد.",
                        severity: "success",
                      });
                    }
                  });
                }}
              >
                <Typography variant="body2" textAlign="left" fontWeight={600}>
                  حذف
                </Typography>
              </Button>
            </Tooltip>
          </Grid>
        </div>
      </Popover>
    </div>
  );
};
