import {
  Button,
  IconButton,
  Popover,
  List,
  ListItemButton,
  ListItemIcon,
  ListItemText,
} from "@mui/material";
import { Grid } from "../../../../components/grid/Grid";
import DeleteIcon from "@mui/icons-material/Delete";
import EditIcon from "@mui/icons-material/Edit";
import DoneOutlineIcon from "@mui/icons-material/DoneOutline";
import DoNotDisturbIcon from "@mui/icons-material/DoNotDisturb";
import { useDispatch } from "react-redux";
import {
  CLOSE_MODAL,
  DRAWER,
  OPEN_MODAL,
} from "../../../../lib/redux/slices/appSlice";
import { SlaughterSubmitFreeBuy } from "../slaughter-submit-free-buy/SlaughterSubmitFreeBuy";
import { slaughterDeleteFreeBuyService } from "../../services/slaughter-delete-free-buy";
import { useContext, useState } from "react";
import { AppContext } from "../../../../contexts/AppContext";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { ProviceRejectFreeBuy } from "../province-reject-free-buy/ProvinceRejectFreeBuy";
import { ProvinceAcceptDirectBuy } from "../../../province/components/province-accept-direct-buy/ProvinceAcceptDirectBuy";
import TuneIcon from "@mui/icons-material/Tune";
import ThumbUpAltIcon from "@mui/icons-material/ThumbUpAlt";
import SmsIcon from "@mui/icons-material/Sms";
import { slaughterEditFreeBuyService } from "../../services/slaughter-edit-free-buy";
import { slaughterResendDirectBuyingSmsService } from "../../services/slaughter-resend-direct-buying-sms";

export const SlaughterFreeBuyOperations = ({
  item,
  updateTable,
  poultryCodeMandatory,
}) => {
  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 showOnlyDelete = poultryCodeMandatory && !item?.inputDirectBuyingCode;

  const handleApproveRequest = () => {
    dispatch(
      OPEN_MODAL({
        title: "تایید فروش مستقیم",
        content: (
          <ProvinceAcceptDirectBuy item={item} updateTable={updateTable} />
        ),
      })
    );
  };

  const handleRejectRequest = () => {
    dispatch(
      OPEN_MODAL({
        title: "رد درخواست فروش آزاد",
        content: <ProviceRejectFreeBuy item={item} updateTable={updateTable} />,
      })
    );
  };

  const handleFinalAccept = () => {
    dispatch(
      OPEN_MODAL({
        title: "آیا مطمئن هستید؟",
        content: (
          <Grid container>
            <Button
              variant="contained"
              onClick={() => {
                dispatch(
                  slaughterEditFreeBuyService({
                    role: getRoleFromUrl(),
                    kill_request_key: item?.key,
                    final_accept: true,
                  })
                ).then((r) => {
                  if (r?.payload?.error) {
                    openNotif({
                      vertical: "top",
                      horizontal: "center",
                      msg: r?.payload?.error,
                      severity: "error",
                    });
                  } else {
                    dispatch(CLOSE_MODAL());
                    updateTable();
                    openNotif({
                      vertical: "top",
                      horizontal: "center",
                      msg: "عملیات با موفقیت انجام شد.",
                      severity: "success",
                    });
                  }
                });
              }}
            >
              تایید
            </Button>
            <Button
              onClick={() => {
                dispatch(CLOSE_MODAL());
              }}
            >
              لغو
            </Button>
          </Grid>
        ),
      })
    );
  };

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

  const handleResendSms = () => {
    dispatch(
      slaughterResendDirectBuyingSmsService({
        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",
        });
      }
    });
  };

  const handleDelete = () => {
    dispatch(slaughterDeleteFreeBuyService(item.key)).then((r) => {
      if (r.error) {
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: r.error,
          severity: "error",
        });
      } else {
        updateTable();
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: "عملیات با موفقیت انجام شد.",
          severity: "success",
        });
        dispatch(
          DRAWER({
            right: false,
            bottom: false,
            left: false,
            content: null,
          })
        );
      }
    });
  };

  const options = [];

  if (
    !showOnlyDelete &&
    (getRoleFromUrl() === "ProvinceOperator" ||
      getRoleFromUrl() === "SuperAdmin" ||
      getRoleFromUrl() === "AdminX")
  ) {
    options.push({
      key: "approve",
      label: "تایید درخواست",
      color: "success.main",
      icon: <DoneOutlineIcon fontSize="small" />,
      action: handleApproveRequest,
    });

    options.push({
      key: "reject",
      label: "رد درخواست",
      color: "warning.main",
      icon: <DoNotDisturbIcon fontSize="small" />,
      action: handleRejectRequest,
    });
  }

  if (getRoleFromUrl() === "KillHouse" && !item?.finalAccept) {
    options.push({
      key: "finalAccept",
      label: "تایید نهایی",
      color: "primary.main",
      icon: <ThumbUpAltIcon fontSize="small" />,
      action: handleFinalAccept,
    });

    options.push({
      key: "edit",
      label: "ویرایش",
      color: "info.main",
      icon: <EditIcon fontSize="small" />,
      action: handleEdit,
    });
  }

  if (showOnlyDelete && item?.finalAccept) {
    options.push({
      key: "resendSms",
      label: "ارسال مجدد پیامک",
      color: "info.main",
      icon: <SmsIcon fontSize="small" />,
      action: handleResendSms,
    });
  }

  options.push({
    key: "delete",
    label: "حذف",
    color: "error.main",
    icon: <DeleteIcon fontSize="small" />,
    action: handleDelete,
  });

  return (
    <Grid container>
      <IconButton
        size="small"
        disabled={
          item?.directBuyingState === "accepted" ||
          (!showOnlyDelete &&
            (getRoleFromUrl() === "KillHouse" && item?.finalAccept
              ? true
              : item?.directBuyingState !== "pending"))
        }
        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: 130, p: 0.5 }}>
          {options.map((option) => (
            <ListItemButton
              key={option.key}
              onClick={() => {
                handleClose();
                option.action();
              }}
              sx={{
                borderRadius: 1,
                mb: 0.25,
                py: 0.5,
                color: option.color,
                "&:last-of-type": {
                  mb: 0,
                },
              }}
            >
              <ListItemIcon sx={{ color: option.color, minWidth: 32 }}>
                {option.icon}
              </ListItemIcon>
              <ListItemText
                primary={option.label}
                primaryTypographyProps={{
                  sx: {
                    color: option.color,
                    fontSize: "0.82rem",
                    fontWeight: 600,
                  },
                }}
              />
            </ListItemButton>
          ))}
        </List>
      </Popover>
    </Grid>
  );
};
