import { Box, IconButton, Popover, Tooltip, Typography } from "@mui/material";
import { Grid } from "../../../../components/grid/Grid";
import DoneOutlineIcon from "@mui/icons-material/DoneOutline";
import CloudUploadIcon from "@mui/icons-material/CloudUpload";
import { useDispatch } from "react-redux";
import { DRAWER, OPEN_MODAL } from "../../../../lib/redux/slices/appSlice";
import { useContext, useState } from "react";
import { AppContext } from "../../../../contexts/AppContext";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import TuneIcon from "@mui/icons-material/Tune";
import { killhouseFreeBuyEditPayment } from "../../services/killhouse-free-buy-edit-payment";
import DoneAllIcon from "@mui/icons-material/DoneAll";
import ArchiveIcon from "@mui/icons-material/Archive";
import EventRepeatIcon from "@mui/icons-material/EventRepeat";
import CloseIcon from "@mui/icons-material/Close";
import { ProvinceSettlementRejectSettlement } from "../province-settlement-reject-settlement/ProvinceSettlementRejectSettlement";
import { ProvinceSettlementExtendSettlement } from "../province-settlement-extend-settlement/ProvinceSettlementExtendSettlement";
import { ProvinceSettlementSubmitDocument } from "../province-settlement-submit-document/ProvinceSettlementSubmitDocument";
import { alpha, useTheme } from "@mui/material/styles";

export const ProvinceSettlementOperation = ({
  item,
  item_key,
  updateTable_data,
}) => {
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);
  const [anchorEl, setAnchorEl] = useState(null);
  const theme = useTheme();
  const role = getRoleFromUrl();
  const isKillHouse = role === "KillHouse";
  const isFinalAccepted = item?.finalAccept === true;
  const isPaymentActionDisabled = !item?.paymentDeadlineState === "pending";
  const isUploadDisabled = isKillHouse ? isFinalAccepted : false;
  const showFinalApprovalAction = isFinalAccepted !== true || isKillHouse;
  const showApproveRequestAction = !isKillHouse && isFinalAccepted;
  const showExtendDeadlineAction = !isKillHouse;
  const showRejectAction = !isKillHouse && isFinalAccepted;
  const showArchiveAction = !isKillHouse;

  const renderAction = ({
    title,
    IconComponent,
    colorKey,
    onClick,
    disabled = false,
    hidden = false,
  }) => {
    if (hidden) {
      return null;
    }

    const paletteMain =
      theme.palette[colorKey]?.main ?? theme.palette.primary.main;
    const hoverBackground = alpha(paletteMain, 0.1);

    const handleActivation = () => {
      if (disabled) {
        return;
      }
      onClick();
    };

    const handleKeyDown = (event) => {
      if (event.key === "Enter" || event.key === " ") {
        event.preventDefault();
        handleActivation();
      }
    };

    return (
      <Grid item>
        <Tooltip title={title} placement="right">
          <span style={{ width: "100%", display: "block" }}>
            <Box
              role="button"
              tabIndex={0}
              onClick={handleActivation}
              onKeyDown={handleKeyDown}
              sx={{
                display: "flex",
                alignItems: "center",
                gap: 1.5,
                px: 1.5,
                py: 1,
                borderRadius: 1,
                cursor: disabled ? "not-allowed" : "pointer",
                opacity: disabled ? 0.4 : 1,
                transition: "background-color 0.2s ease",
                "&:hover": {
                  backgroundColor: disabled ? "transparent" : hoverBackground,
                },
              }}
            >
              <IconComponent sx={{ color: paletteMain }} />
              <Typography
                variant="body2"
                sx={{ color: paletteMain, fontWeight: 500 }}
              >
                {title}
              </Typography>
            </Box>
          </span>
        </Tooltip>
      </Grid>
    );
  };

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

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

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

  // const isReject = item?.paymentDeadlineState === "pending";

  const handleFinalApproval = (payload) => {
    handleClose();

    const settlementAmount = item?.generalInfo?.totalPaidAmount || 0;
    const totalPrice = item?.generalInfo?.totalAmount || 0;

    const minimumPrice = (parseInt(totalPrice) / 100) * 90;
    const maximumPrice =
      (parseInt(totalPrice) / 100) * 10 + parseInt(totalPrice);

    if (settlementAmount < minimumPrice || settlementAmount > maximumPrice) {
      openNotif({
        vertical: "top",
        horizontal: "center",
        msg: "مبلغ تسویه با شروط تسویه حساب مطابقت ندارد",
        severity: "error",
      });
      return;
    }

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

  const handleReject = (type) => {
    handleClose();

    dispatch(
      OPEN_MODAL({
        title: type === "reject" ? "برگشت درخواست" : "بایگانی درخواست",
        content: (
          <ProvinceSettlementRejectSettlement
            updateTable_data={updateTable_data}
            item={item}
            type={type}
          />
        ),
      })
    );
  };

  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}
      >
        <Grid style={{ padding: "10px 6px" }}>
          <Grid container direction="column" spacing={1}>
            {renderAction({
              title: "بارگذاری سند",
              IconComponent: CloudUploadIcon,
              colorKey: "success",
              disabled: isUploadDisabled,
              onClick: () => {
                handleClose();
                dispatch(
                  DRAWER({
                    title: "بارگزاری سند",
                    top: !(window.innerWidth <= 600),
                    bottom: window.innerWidth <= 600,
                    size: 1000,
                    content: (
                      <ProvinceSettlementSubmitDocument
                        item={item}
                        modal_key={item_key}
                        updateTable_modal={updateTable_data}
                      />
                    ),
                  })
                );
              },
            })}

            {renderAction({
              title: "تایید نهایی",
              IconComponent: DoneOutlineIcon,
              colorKey: "success",
              disabled: isFinalAccepted,
              hidden: !showFinalApprovalAction,
              onClick: () =>
                handleFinalApproval({
                  key: item.key,
                  final_accept: true,
                  role,
                }),
            })}

            {renderAction({
              title: "تایید درخواست",
              IconComponent: DoneAllIcon,
              colorKey: "primary",
              hidden: !showApproveRequestAction,
              onClick: () =>
                handleFinalApproval({
                  key: item.key,
                  state: "accepted",
                  role,
                  check: true,
                }),
            })}

            {renderAction({
              title: "تمدید مهلت تسویه",
              IconComponent: EventRepeatIcon,
              colorKey: "primary",
              hidden: !showExtendDeadlineAction,
              disabled: isPaymentActionDisabled,
              onClick: () => {
                handleClose();
                dispatch(
                  OPEN_MODAL({
                    title: "تمدید مهلت تسویه",
                    content: (
                      <ProvinceSettlementExtendSettlement
                        updateTable_data={updateTable_data}
                        item={item}
                      />
                    ),
                  })
                );
              },
            })}

            {renderAction({
              title: "رد درخواست",
              IconComponent: CloseIcon,
              colorKey: "error",
              hidden: !showRejectAction,
              disabled: isPaymentActionDisabled,
              onClick: () => handleReject("reject"),
            })}

            {renderAction({
              title: "بایگانی",
              IconComponent: ArchiveIcon,
              colorKey: "error",
              hidden: !showArchiveAction,
              disabled: isPaymentActionDisabled,
              onClick: () => handleReject("archive"),
            })}
          </Grid>
        </Grid>
      </Popover>
    </Grid>
  );
};
