import { useContext, useState } from "react";
import { Grid } from "../../../../components/grid/Grid";
import {
  Button,
  IconButton,
  Popover,
  Tooltip,
  Typography,
} from "@mui/material";
import TuneIcon from "@mui/icons-material/Tune";
import ReceiptLongIcon from "@mui/icons-material/ReceiptLong";
import { CLOSE_MODAL, OPEN_MODAL } from "../../../../lib/redux/slices/appSlice";
import { useDispatch } from "react-redux";
import { slaughterNoneRecieptService } from "../../services/slaughter-none-reciept-operation";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { AppContext } from "../../../../contexts/AppContext";
import { SlaughterNoneRecieptModal } from "../slaughter-none-reciept-modal/SlaughterNoneRecieptModal";
import RestoreIcon from "@mui/icons-material/Restore";
import { SlaughterRecieptBackModal } from "../slaughter-none-reciept-back-modal/SlaughterRecieptBackModal";
import { slaughterNoneBackRecieptService } from "../../services/slaughter-none-back-reciept";

export const SlaughterNoneRecieptOperation = ({ item, updateTable }) => {
  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 handleSubmit = (values) => {
    dispatch(
      slaughterNoneRecieptService({
        key: item?.key,
        role: getRoleFromUrl(),
        state: values.state,
        message: values.message,
      })
    ).then((r) => {
      dispatch(CLOSE_MODAL());
      if (r.payload.error) {
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: r.payload.error,
          severity: "error",
        });
      } else {
        handleClose();
        updateTable();
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: "عملیات با موفقیت انجام شد.",
          severity: "success",
        });
      }
    });
  };

  const handleBackSubmit = (values) => {
    dispatch(
      slaughterNoneBackRecieptService({
        key: item?.key,
        non_receipt: false,
        non_receipt_return: true,
        non_receipt_return_message: values.message,
      })
    ).then((r) => {
      dispatch(CLOSE_MODAL());
      if (r.payload.error) {
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: r.payload.error,
          severity: "error",
        });
      } else {
        handleClose();
        updateTable();
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: "عملیات با موفقیت انجام شد.",
          severity: "success",
        });
      }
    });
  };

  return (
    <Grid>
      <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}
      >
        <Grid
          style={{ padding: "10px", width: "200px" }}
          container
          direction="column"
          alignItems="flex-start"
        >
          {["ProvinceOperator", "SuperAdmin", "AdminX"].includes(
            getRoleFromUrl()
          ) && (
            <Tooltip
              title={"تایید / رد عدم وصول کشتارگاه"}
              placement="left-start"
            >
              <Button
                // variant="outlined"
                disabled={item?.nonReceiptState !== "pending"}
                size="small"
                color="primary"
                startIcon={<ReceiptLongIcon fontSize="small" />}
                onClick={() => {
                  handleClose();
                  dispatch(
                    OPEN_MODAL({
                      title: "تایید / رد عدم وصول کشتارگاه",
                      content: (
                        <SlaughterNoneRecieptModal
                          handleSubmit={handleSubmit}
                          item={item}
                        />
                      ),
                    })
                  );
                }}
              >
                <Typography variant="body2" textAlign="left" fontWeight={600}>
                  تایید / رد عدم وصول کشتارگاه
                </Typography>
              </Button>
            </Tooltip>
          )}
          <Tooltip title={"برگشت عدم وصول"} placement="left-start">
            <Button
              // variant="outlined"
              disabled={item?.registrationCode}
              size="small"
              color="error"
              startIcon={<RestoreIcon fontSize="small" />}
              onClick={() => {
                handleClose();
                dispatch(
                  OPEN_MODAL({
                    title: "برگشت عدم وصول",
                    content: (
                      <SlaughterRecieptBackModal
                        handleSubmit={handleBackSubmit}
                        item={item}
                      />
                    ),
                  })
                );
              }}
            >
              <Typography variant="body2" textAlign="left" fontWeight={600}>
                برگشت عدم وصول
              </Typography>
            </Button>
          </Tooltip>
        </Grid>
      </Popover>
    </Grid>
  );
};
