import React, { useContext, useState } from "react";
import {
  Button,
  IconButton,
  List,
  ListItemButton,
  ListItemIcon,
  ListItemText,
  Popover,
} from "@mui/material";
import TuneIcon from "@mui/icons-material/Tune";
import EditOutlinedIcon from "@mui/icons-material/EditOutlined";
import DeleteOutlineIcon from "@mui/icons-material/DeleteOutline";
import ReplayIcon from "@mui/icons-material/Replay";
import { useDispatch } from "react-redux";
import { Grid } from "../../../../components/grid/Grid";
import {
  slaughterDeleteAllocatedService,
  slaughterReturnAllocatedService,
} from "../../../slaughter-house/services/salughter-delete-allocated";
import { CLOSE_MODAL, OPEN_MODAL } from "../../../../lib/redux/slices/appSlice";
import { ProvinceDispenserEditToGuild } from "../province-dispenser-edit-to-guild/ProvinceDispenserEditToGuild";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { AppContext } from "../../../../contexts/AppContext";

export const ProvinceDispenserSaleWithInProvinceOperation = ({
  fetchApiData,
  item,
  fetchData,
  updateTable,
  priceInfo,
  fetchDashboardData,
  isAccepted,
}) => {
  const [anchorEl, setAnchorEl] = useState(null);
  const dispatch = useDispatch();

  const [openNotif] = useContext(AppContext);

  const handleClick = (event) => {
    setAnchorEl(event.currentTarget);
  };

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

  const handleEditClick = () => {
    handleClose(true);
    dispatch(
      OPEN_MODAL({
        title: "ویرایش تخصیص",
        content: (
          <ProvinceDispenserEditToGuild
            fetchData={fetchData}
            updateTable={updateTable}
            fetchApiData={fetchApiData}
            editData={item}
            priceInfo={priceInfo}
            fetchDashboardData={fetchDashboardData}
          />
        ),
      })
    );
  };

  const handleDeleteClick = () => {
    dispatch(
      OPEN_MODAL({
        title: "آیا مطمئن هستید؟",
        content: (
          <Grid container>
            <Button
              variant="contained"
              onClick={() => {
                dispatch(
                  slaughterDeleteAllocatedService({
                    steward_allocation_key: item.key,
                  })
                ).then((r) => {
                  if (r.payload.error) {
                    openNotif({
                      vertical: "top",
                      horizontal: "center",
                      msg: r.payload.error,
                      severity: "error",
                    });
                  } else {
                    dispatch(CLOSE_MODAL());

                    fetchApiData(1);
                    setAnchorEl(null);
                    openNotif({
                      vertical: "top",
                      horizontal: "center",
                      msg: "عملیات با موفقیت انجام شد.",
                      severity: "success",
                    });
                  }
                });
              }}
            >
              تایید
            </Button>
            <Button
              onClick={() => {
                dispatch(CLOSE_MODAL());
              }}
            >
              لغو
            </Button>
          </Grid>
        ),
      })
    );
  };

  const handleReturnClick = () => {
    dispatch(
      OPEN_MODAL({
        title: "آیا مطمئن هستید؟",
        content: (
          <Grid container>
            <Button
              variant="contained"
              onClick={() => {
                dispatch(
                  slaughterReturnAllocatedService({
                    key: item.key,
                  })
                ).then((r) => {
                  if (r.payload.error) {
                    openNotif({
                      vertical: "top",
                      horizontal: "center",
                      msg: r.payload.error,
                      severity: "error",
                    });
                  } else {
                    dispatch(CLOSE_MODAL());

                    fetchApiData(1);
                    setAnchorEl(null);
                    openNotif({
                      vertical: "top",
                      horizontal: "center",
                      msg: "عملیات با موفقیت انجام شد.",
                      severity: "success",
                    });
                  }
                });
              }}
            >
              تایید
            </Button>
            <Button
              onClick={() => {
                dispatch(CLOSE_MODAL());
              }}
            >
              لغو
            </Button>
          </Grid>
        ),
      })
    );
  };

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

  return (
    <Grid container>
      <IconButton
        disabled={
          (item?.receiverState === "accepted" ||
            item?.loggedRegistrationCode) &&
          !getRoleFromUrl() === "SuperAdmin" &&
          !getRoleFromUrl() === "AdminX"
        }
        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={{ py: 0 }}>
          {isAccepted ? (
            <>
              <ListItemButton onClick={handleEditClick}>
                <ListItemIcon>
                  <EditOutlinedIcon fontSize="small" color="primary" />
                </ListItemIcon>
                <ListItemText
                  primary="ویرایش"
                  primaryTypographyProps={{
                    variant: "body2",
                    color: "primary",
                  }}
                />
              </ListItemButton>
              <ListItemButton onClick={handleDeleteClick}>
                <ListItemIcon>
                  <DeleteOutlineIcon fontSize="small" color="error" />
                </ListItemIcon>
                <ListItemText
                  primary="حذف"
                  primaryTypographyProps={{ variant: "body2", color: "error" }}
                />
              </ListItemButton>
            </>
          ) : (
            <ListItemButton onClick={handleReturnClick}>
              <ListItemIcon>
                <ReplayIcon fontSize="small" color="error" />
              </ListItemIcon>
              <ListItemText
                primary="برگشت"
                primaryTypographyProps={{ variant: "body2", color: "error" }}
              />
            </ListItemButton>
          )}
        </List>
      </Popover>
    </Grid>
  );
};
