import React, { useContext, useState } from "react";
import { useDispatch } from "react-redux";
import { AppContext } from "../../../../contexts/AppContext";
import { Grid } from "../../../../components/grid/Grid";
import {
  Button,
  IconButton,
  Popover,
  List,
  ListItemButton,
  ListItemIcon,
  ListItemText,
  Typography,
} from "@mui/material";
import TuneIcon from "@mui/icons-material/Tune";
import {
  CLOSE_MODAL,
  DRAWER,
  OPEN_MODAL,
} from "../../../../lib/redux/slices/appSlice";
import { provinceOutRequestCancelRequest } from "../../services/provinceOutRequestCancelRequest";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { ProvinceFreeSaleEditRequest } from "../province-free-sale-edit-request/ProvinceFreeSaleEditRequest";
import EditIcon from "@mui/icons-material/Edit";
import CloseIcon from "@mui/icons-material/Close";

export const ProvinceFreeSalesAcceptedRequestsOperations = ({
  fetchApiData,
  item,
}) => {
  const dispatch = useDispatch();

  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 [openNotif] = useContext(AppContext);
  const role = getRoleFromUrl();

  const handleEdit = () => {
    handleClose();
    dispatch(
      DRAWER({
        title: "ویرایش درخواست",
        right: !(window.innerWidth <= 600),
        bottom: window.innerWidth <= 600,
        content: (
          <ProvinceFreeSaleEditRequest
            item={item}
            fetchApiData={fetchApiData}
          />
        ),
      })
    );
  };

  const handleCancelRequest = () => {
    handleClose();
    dispatch(
      OPEN_MODAL({
        title: "آیا از لغو درخواست مطمئن هستید؟",
        content: (
          <Grid>
            <Button
              variant="contained"
              onClick={() => {
                dispatch(
                  provinceOutRequestCancelRequest({
                    role,
                    poultry_request_key: item.key,
                  })
                ).then((r) => {
                  if (r.payload.error) {
                    openNotif({
                      vertical: "top",
                      horizontal: "center",
                      msg: r.payload.error,
                      severity: "error",
                    });
                  } else {
                    fetchApiData(1);
                    openNotif({
                      vertical: "top",
                      horizontal: "center",
                      msg: "عملیات با موفقیت انجام شد.",
                      severity: "success",
                    });
                  }
                });
                dispatch(CLOSE_MODAL());
              }}
            >
              بله
            </Button>
            <Button
              onClick={() => {
                dispatch(CLOSE_MODAL());
              }}
            >
              خیر
            </Button>
          </Grid>
        ),
      })
    );
  };

  const options = [
    {
      key: "edit",
      label: "ویرایش",
      color: "primary.main",
      icon: <EditIcon />,
      action: handleEdit,
      disabled: Boolean(item.quarantineCode || item?.outState === "پرداخت شده"),
    },
    {
      key: "cancel",
      label: "لغو",
      color: "error.main",
      icon: <CloseIcon />,
      action: handleCancelRequest,
      disabled:
        !item.provinceState === "pending" ||
        !item.provinceState === "accepted" ||
        item?.outState === "پرداخت شده" ||
        item.quarantineCode,
    },
  ];

  return (
    <Grid container>
      <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}
      >
        <List sx={{ width: 220, p: 1 }}>
          {options.map((option) => (
            <ListItemButton
              key={option.key}
              onClick={() => {
                if (option.disabled) {
                  return;
                }
                option.action();
              }}
              disabled={Boolean(option.disabled)}
              sx={{
                borderRadius: 1,
                mb: 0.5,
                color: option.disabled ? "text.disabled" : option.color,
                "&:last-of-type": {
                  mb: 0,
                },
              }}
            >
              <ListItemIcon
                sx={{
                  color: option.disabled ? "text.disabled" : option.color,
                  minWidth: 40,
                }}
              >
                {option.icon}
              </ListItemIcon>
              <ListItemText
                primary={
                  <Typography
                    sx={{
                      color: option.disabled ? "text.disabled" : option.color,
                      fontWeight: 600,
                    }}
                  >
                    {option.label}
                  </Typography>
                }
              />
            </ListItemButton>
          ))}
        </List>
      </Popover>
    </Grid>
  );
};
