import {
  IconButton,
  Popover,
  List,
  ListItemButton,
  ListItemIcon,
  ListItemText,
  Typography,
} from "@mui/material";
import React, { useContext, useState } from "react";
import { useDispatch } from "react-redux";
import SettingsIcon from "@mui/icons-material/Settings";
import TuneIcon from "@mui/icons-material/Tune";
import DeleteIcon from "@mui/icons-material/Delete";
import EditIcon from "@mui/icons-material/Edit";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { ChainsAllocation } from "../chains-allocation/ChainsAllocation";
import { provinceChainsDeleteAllocation } from "../../services/province-chains-delete-allocation";
import { AppContext } from "../../../../contexts/AppContext";
import { ProvinceCheckChainAllocation } from "../province-check-chain-allocation/ProvinceCheckChainAllocation";
import { DRAWER } from "../../../../lib/redux/slices/appSlice";

export const ChainBarManagementOperations = ({ item, fetchApiData }) => {
  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 role = getRoleFromUrl();

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

  const handleEdit = () => {
    handleClose();
    dispatch(
      DRAWER({
        title: "ویرایش بار",
        right: !(window.innerWidth <= 600),
        bottom: window.innerWidth <= 600,
        content: (
          <ChainsAllocation item={item} updateTable={fetchApiData} isEdit />
        ),
      })
    );
  };

  const handleDelete = () => {
    handleClose();
    dispatch(provinceChainsDeleteAllocation(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(1);
      }
    });
  };

  const canManage =
    role === "ProvinceOperator" || role === "SuperAdmin" || role === "AdminX";

  const options = [
    {
      key: "approve",
      label: "تایید / رد درخواست",
      color: "primary.main",
      icon: <SettingsIcon sx={{ fontSize: { xs: 20, md: 18 } }} />,
      action: handleApprove,
      disabled: item?.state !== "pending",
    },
    {
      key: "edit",
      label: "ویرایش بار",
      color: "info.main",
      icon: <EditIcon sx={{ fontSize: { xs: 20, md: 18 } }} />,
      action: handleEdit,
      disabled:
        !canManage ||
        item?.state === "rejected" ||
        Boolean(item?.quarantineCode),
    },
    {
      key: "delete",
      label: "حذف بار",
      color: "error.main",
      icon: <DeleteIcon sx={{ fontSize: { xs: 20, md: 18 } }} />,
      action: handleDelete,
      disabled:
        !canManage ||
        item?.state === "rejected" ||
        Boolean(item?.quarantineCode),
    },
  ];

  return (
    <div>
      <IconButton
        aria-describedby={id}
        variant="contained"
        color="primary"
        onClick={handleClick}
      >
        <TuneIcon />
      </IconButton>
      <Popover
        anchorOrigin={{
          vertical: "bottom",
          horizontal: "right",
        }}
        transformOrigin={{
          vertical: "top",
          horizontal: "left",
        }}
        slotProps={{
          paper: {
            sx: {
              mt: 1,
            },
          },
        }}
        id={id}
        open={open}
        anchorEl={anchorEl}
        onClose={handleClose}
      >
        <List sx={{ 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: 36,
                }}
              >
                {option.icon}
              </ListItemIcon>
              <ListItemText
                primary={
                  <Typography
                    sx={{
                      color: option.disabled ? "text.disabled" : option.color,
                      fontWeight: 600,
                      fontSize: { xs: "13px", md: "14px" },
                    }}
                  >
                    {option.label}
                  </Typography>
                }
              />
            </ListItemButton>
          ))}
        </List>
      </Popover>
    </div>
  );
};
