import { Button, IconButton, Popover, Tooltip } from "@mui/material";
import { Grid } from "../../../../components/grid/Grid";

import { useDispatch } from "react-redux";
import { CLOSE_MODAL, OPEN_MODAL } from "../../../../lib/redux/slices/appSlice";
import VpnKeyIcon from "@mui/icons-material/VpnKey";
import { useContext, useState } from "react";
import { AppContext } from "../../../../contexts/AppContext";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import TuneIcon from "@mui/icons-material/Tune";
import EditIcon from "@mui/icons-material/Edit";
import DeleteIcon from "@mui/icons-material/Delete";
import ThumbUpAltIcon from "@mui/icons-material/ThumbUpAlt";
import DoNotDisturbIcon from "@mui/icons-material/DoNotDisturb";
import DoneOutlineIcon from "@mui/icons-material/DoneOutline";
import { provinceDeleteTradePanelService } from "../../services/province-delete-trade-panel";
import TradePanelPurchaseModal from "../trade-panel-purchase-modal/TradePanelPurchaseModal";
import { ProvinceMarketRequestFinalAcceptService } from "../../services/province-market-request-final-accept";
import { ProvinceTradePanelEnterMarketCode } from "../province-trade-panel-enter-market-code/ProvinceTradePanelEnterMarketCode";
export const ProvinceDirectBuyOperation = ({
  item,
  updateTable,
  updateTable2,
}) => {
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);

  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 updateAll = () => {
    updateTable();
    updateTable2();
  };

  return (
    <Grid container>
      <IconButton
        disabled={
          getRoleFromUrl() !== "KillHouse"
            ? item?.marketFinalAccept === false
              ? true
              : item.marketState !== "pending"
            : item?.marketFinalAccept === false
            ? false
            : item?.marketCodeStatus === true &&
              !item?.inputMarketCode &&
              item.marketState === "pending"
            ? false
            : true
        }
        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",
            display: "flex",
            flexDirection: "column",
          }}
        >
          <Grid container direction="column">
            {getRoleFromUrl() === "KillHouse" &&
              item?.marketCodeStatus === true &&
              !item?.inputMarketCode &&
              item?.marketFinalAccept === true && (
                <Tooltip title="ورود کد احراز" placement="right">
                  <IconButton
                    color="primary"
                    onClick={() => {
                      handleClose();
                      dispatch(
                        OPEN_MODAL({
                          title: "ورود کد احراز",
                          content: (
                            <ProvinceTradePanelEnterMarketCode
                              item={item}
                              updateAll={updateAll}
                            />
                          ),
                        })
                      );
                    }}
                  >
                    <VpnKeyIcon />
                  </IconButton>
                </Tooltip>
              )}

            {getRoleFromUrl() === "KillHouse" && !item?.marketFinalAccept && (
              <Tooltip title="تایید نهایی" placement="right">
                <IconButton
                  color="primary"
                  onClick={() => {
                    handleClose();
                    dispatch(
                      OPEN_MODAL({
                        title: "آیا مطمئن هستید؟",
                        content: (
                          <Grid container>
                            <Button
                              variant="contained"
                              onClick={() => {
                                dispatch(
                                  ProvinceMarketRequestFinalAcceptService({
                                    key: item?.key,
                                    market_final_accept: true,
                                  })
                                ).then((r) => {
                                  if (r?.payload?.error) {
                                    openNotif({
                                      vertical: "top",
                                      horizontal: "center",
                                      msg: r?.payload?.error,
                                      severity: "error",
                                    });
                                  } else {
                                    dispatch(CLOSE_MODAL());
                                    updateAll();
                                    openNotif({
                                      vertical: "top",
                                      horizontal: "center",
                                      msg: "عملیات با موفقیت انجام شد.",
                                      severity: "success",
                                    });
                                  }
                                });
                              }}
                            >
                              تایید
                            </Button>
                            <Button
                              onClick={() => {
                                dispatch(CLOSE_MODAL());
                              }}
                            >
                              لغو
                            </Button>
                          </Grid>
                        ),
                      })
                    );
                  }}
                >
                  <ThumbUpAltIcon />
                </IconButton>
              </Tooltip>
            )}

            {getRoleFromUrl() === "KillHouse" &&
              item?.marketFinalAccept === false && (
                <Tooltip title="ویرایش خرید" placement="right">
                  <IconButton
                    color="primary"
                    onClick={() => {
                      handleClose();
                      dispatch(
                        OPEN_MODAL({
                          title: "ویرایش خرید",
                          content: (
                            <TradePanelPurchaseModal
                              key="purchase"
                              item={item}
                              updateTable={updateAll}
                              isEdit={true}
                            />
                          ),
                        })
                      );
                    }}
                  >
                    <EditIcon />
                  </IconButton>
                </Tooltip>
              )}
            {getRoleFromUrl() === "KillHouse" && (
              <Tooltip title="حذف" placement="right">
                <IconButton
                  color="error"
                  onClick={() => {
                    handleClose();
                    dispatch(
                      OPEN_MODAL({
                        title: "آیا مطمئن هستید؟",
                        content: (
                          <Grid container>
                            <Button
                              variant="contained"
                              onClick={() => {
                                dispatch(
                                  provinceDeleteTradePanelService(item.key)
                                ).then((r) => {
                                  if (r.error) {
                                    openNotif({
                                      vertical: "top",
                                      horizontal: "center",
                                      msg: r.error,
                                      severity: "error",
                                    });
                                  } else {
                                    updateAll();
                                    dispatch(CLOSE_MODAL());
                                    openNotif({
                                      vertical: "top",
                                      horizontal: "center",
                                      msg: "عملیات با موفقیت انجام شد.",
                                      severity: "success",
                                    });
                                  }
                                });
                              }}
                            >
                              تایید
                            </Button>
                            <Button
                              onClick={() => {
                                dispatch(CLOSE_MODAL());
                              }}
                            >
                              لغو
                            </Button>
                          </Grid>
                        ),
                      })
                    );
                  }}
                >
                  <DeleteIcon />
                </IconButton>
              </Tooltip>
            )}

            {(getRoleFromUrl() === "ProvinceOperator" ||
              getRoleFromUrl() === "SuperAdmin" ||
              getRoleFromUrl() === "AdminX") && (
              <Tooltip title="تایید" placement="right">
                <IconButton
                  disabled={
                    getRoleFromUrl() === "KillHouse" &&
                    item?.marketFinalAccept === true
                  }
                  color="primary"
                  onClick={() => {
                    handleClose();
                    dispatch(
                      OPEN_MODAL({
                        title: "آیا مطمئن هستید؟",
                        content: (
                          <Grid container>
                            <Button
                              variant="contained"
                              onClick={() => {
                                dispatch(
                                  ProvinceMarketRequestFinalAcceptService({
                                    key: item?.key,
                                    check: true,
                                    market_state: "accepted",
                                    market_state_message: "تایید",
                                  })
                                ).then((r) => {
                                  if (r?.payload?.error) {
                                    openNotif({
                                      vertical: "top",
                                      horizontal: "center",
                                      msg: r?.payload?.error,
                                      severity: "error",
                                    });
                                  } else {
                                    dispatch(CLOSE_MODAL());
                                    updateAll();
                                    openNotif({
                                      vertical: "top",
                                      horizontal: "center",
                                      msg: "عملیات با موفقیت انجام شد.",
                                      severity: "success",
                                    });
                                  }
                                });
                              }}
                            >
                              تایید
                            </Button>
                            <Button
                              onClick={() => {
                                dispatch(CLOSE_MODAL());
                              }}
                            >
                              لغو
                            </Button>
                          </Grid>
                        ),
                      })
                    );
                  }}
                >
                  <DoneOutlineIcon />
                </IconButton>
              </Tooltip>
            )}

            {(getRoleFromUrl() === "ProvinceOperator" ||
              getRoleFromUrl() === "SuperAdmin" ||
              getRoleFromUrl() === "AdminX") && (
              <Tooltip title="رد" placement="right">
                <IconButton
                  color="error"
                  onClick={() => {
                    handleClose();
                    dispatch(
                      OPEN_MODAL({
                        title: "آیا مطمئن هستید؟",
                        content: (
                          <Grid container>
                            <Button
                              variant="contained"
                              onClick={() => {
                                dispatch(
                                  ProvinceMarketRequestFinalAcceptService({
                                    key: item?.key,
                                    check: true,
                                    market_state: "rejected",
                                    market_state_message: "رد",
                                  })
                                ).then((r) => {
                                  if (r?.payload?.error) {
                                    openNotif({
                                      vertical: "top",
                                      horizontal: "center",
                                      msg: r?.payload?.error,
                                      severity: "error",
                                    });
                                  } else {
                                    dispatch(CLOSE_MODAL());
                                    updateAll();
                                    openNotif({
                                      vertical: "top",
                                      horizontal: "center",
                                      msg: "عملیات با موفقیت انجام شد.",
                                      severity: "success",
                                    });
                                  }
                                });
                              }}
                            >
                              تایید
                            </Button>
                            <Button
                              onClick={() => {
                                dispatch(CLOSE_MODAL());
                              }}
                            >
                              لغو
                            </Button>
                          </Grid>
                        ),
                      })
                    );
                  }}
                >
                  <DoNotDisturbIcon />
                </IconButton>
              </Tooltip>
            )}
          </Grid>
        </div>
      </Popover>
    </Grid>
  );
};
