import React, { useContext, useState } from "react";
import { Button, IconButton, Popover, Tooltip } from "@mui/material";
import { useDispatch } from "react-redux";
import { Grid } from "../../../../components/grid/Grid";
import { AppContext } from "../../../../contexts/AppContext";
import { DRAWER } from "../../../../lib/redux/slices/appSlice";
import { stewardDeleteOutSellService } from "../../../guild/services/steward-sell-out-delete-service";
import { StewardSellOutOfProvinceEditSell } from "../steward-purchase-out-province-edit-sell/StewardSellOutOfProvinceEditSell";
import { fetchStewardBroadcastAndProducts } from "../../services/handle-fetch-steward-products";
import { stewardResendOutProvinceRegistrationCodeService } from "../../services/steward-resend-out-province-registration-code";
import TuneIcon from "@mui/icons-material/Tune";
import EditIcon from "@mui/icons-material/Edit";
import DeleteIcon from "@mui/icons-material/Delete";
import SendIcon from "@mui/icons-material/Send";

export const StewardOutProvinceSalesOperations = ({
  item,
  updateTable,
  fetchApiData,
  page,
}) => {
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);
  const [popoverOpen, setPopoverOpen] = useState(false);
  const [anchorEl, setAnchorEl] = useState(null);

  const openPopover = (event) => {
    setPopoverOpen(true);
    setAnchorEl(event.currentTarget);
  };

  const closePopover = () => {
    setPopoverOpen(false);
    setAnchorEl(null);
  };

  const handleEdit = () => {
    closePopover();
    dispatch(
      DRAWER({
        right: !(window.innerWidth <= 600),
        bottom: window.innerWidth <= 600,
        title: "ویرایش فروش خارج از استان",
        content: (
          <StewardSellOutOfProvinceEditSell
            fetchItems={updateTable}
            isEdit={true}
            item={item}
          />
        ),
      })
    );
  };

  const handleDelete = () => {
    closePopover();
    dispatch(stewardDeleteOutSellService(item?.key)).then((r) => {
      if (r.payload.error) {
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: r.payload.data.result,
          severity: "error",
        });
      } else {
        updateTable();
        dispatch(fetchStewardBroadcastAndProducts());
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: r.payload.data.result,
          severity: "success",
        });
      }
    });
  };

  const handleResend = () => {
    closePopover();
    dispatch(
      stewardResendOutProvinceRegistrationCodeService({
        key: item?.key,
      })
    ).then((r) => {
      if (r.payload.error) {
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: r.payload.error,
          severity: "error",
        });
      } else {
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: "کد با موفقیت ارسال شد.",
          severity: "success",
        });
        fetchApiData(page);
      }
    });
  };

  const open = Boolean(anchorEl);
  const id = open ? "popover" : undefined;

  return (
    <div>
      <IconButton
        aria-describedby={id}
        variant="contained"
        color="primary"
        onClick={openPopover}
      >
        <TuneIcon />
      </IconButton>
      <Popover
        anchorOrigin={{
          vertical: "bottom",
          horizontal: "right",
        }}
        transformOrigin={{
          vertical: "top",
          horizontal: "left",
        }}
        id={id}
        open={open}
        anchorEl={anchorEl}
        onClose={closePopover}
      >
        <div style={{ padding: "20px" }}>
          <Grid container direction="column">
            <Tooltip title="ویرایش" placement="left-start">
              <Button
                aria-label="edit"
                color="primary"
                variant="text"
                onClick={handleEdit}
                startIcon={<EditIcon />}
              >
                ویرایش
              </Button>
            </Tooltip>

            <Tooltip title="حذف" placement="left-start">
              <Button
                aria-label="delete"
                color="error"
                variant="text"
                onClick={handleDelete}
                startIcon={<DeleteIcon />}
              >
                حذف
              </Button>
            </Tooltip>

            {item?.systemRegistrationCode &&
              item?.registrationCode &&
              !item?.loggedRegistrationCode && (
                <Tooltip title="ارسال مجدد کد" placement="left-start">
                  <Button
                    aria-label="resend"
                    color="success"
                    variant="text"
                    onClick={handleResend}
                    startIcon={<SendIcon />}
                  >
                    ارسال مجدد کد
                  </Button>
                </Tooltip>
              )}
          </Grid>
        </div>
      </Popover>
    </div>
  );
};
