import { Button, IconButton, Popover, TextField } from "@mui/material";
import { useContext, useState } from "react";
import TuneIcon from "@mui/icons-material/Tune";
import VisibilityIcon from "@mui/icons-material/Visibility";
import CheckIcon from "@mui/icons-material/Check";
import CloseIcon from "@mui/icons-material/Close";
import CheckCircleIcon from "@mui/icons-material/CheckCircle";
import SendIcon from "@mui/icons-material/Send";
import { Grid } from "../../../../components/grid/Grid";
import { SPACING } from "../../../../data/spacing";
import { checkKillhouseRequestGuildService } from "../../services/check-killhouse-request-guild";
import { useDispatch } from "react-redux";
import { AppContext } from "../../../../contexts/AppContext";
import { CLOSE_MODAL, OPEN_MODAL } from "../../../../lib/redux/slices/appSlice";
import { ProvinceManageGuildsSubmitRegisterCode } from "../province-manage-guilds-submit-register-code/ProvinceManageGuildsSubmitRegisterCode";
import { provinceResendRegisterCodeStateService } from "../../services/province-get-register-code-state";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { ViewGuildDetails } from "../view-guild-details/ViewGuildDetails";

export const ManageGuildsRequestsOperations = ({ guild, updateTable }) => {
  const [popoverOpen, setPopoverOpen] = useState(false);
  const [anchorEl, setAnchorEl] = useState(null);

  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);

  const openPopover = (event) => {
    setPopoverOpen(true);
    setAnchorEl(event.currentTarget);
  };

  const closePopover = () => {
    setPopoverOpen(false);
    setAnchorEl(null);
  };

  return (
    <Grid>
      <IconButton variant="contained" color="primary" onClick={openPopover}>
        <TuneIcon />
      </IconButton>
      <Popover
        open={popoverOpen}
        anchorEl={anchorEl}
        onClose={closePopover}
        anchorOrigin={{
          vertical: "bottom",
          horizontal: "right",
        }}
        transformOrigin={{
          vertical: "top",
          horizontal: "left",
        }}
      >
        <div style={{ padding: 10 }}>
          <Grid
            container
            direction="column"
            alignItems="flex-start"
            justifyContent="center"
            gap={1}
          >
            {/* {!readOnly && (
              <Tooltip placement="left" title="بازگشت جوجه ریزی">
                <IconButton
                  variant="outlined"
                  onClick={() => {
                    dispatch(
                      hatchingUndoArchiveService({
                        key: item.key,
                        type: "return_archive",
                      })
                    ).then((r) => {
                      if (r.payload.error) {
                        openNotif({
                          vertical: "top",
                          horizontal: "center",
                          msg: r.payload.error,
                          severity: "error",
                        });
                      } else {
                        updateArchive(1);
                        openNotif({
                          vertical: "top",
                          horizontal: "center",
                          msg: "عملیات با موفقیت انجام شد.",
                          severity: "success",
                        });
                      }
                    });
                  }}
                >
                  <KeyboardReturnIcon />
                </IconButton>
              </Tooltip>
            )} */}

            {["SuperAdmin", "AdminX", "GuildRoom"].includes(
              getRoleFromUrl()
            ) && (
              <Button
                size="small"
                color="info"
                startIcon={<VisibilityIcon />}
                sx={{ fontSize: { xs: 12, md: 15 } }}
                onClick={() => {
                  closePopover();
                  dispatch(
                    OPEN_MODAL({
                      title: "مشاهده جزییات صنف",
                      content: <ViewGuildDetails guild={guild} />,
                      size: window.innerWidth <= 600 ? "small" : "auto",
                    })
                  );
                }}
              >
                جزییات
              </Button>
            )}

            {(guild?.activeRegisterCode && guild?.loggedRegisterCode) ||
            !guild?.activeRegisterCode ? (
              <Grid
                container
                alignItems="flex-start"
                justifyContent="flex-start"
                gap={SPACING.TINY}
                direction="column"
              >
                <Button
                  size="small"
                  color="success"
                  startIcon={<CheckIcon />}
                  sx={{ fontSize: { xs: 12, md: 15 } }}
                  onClick={() => {
                    closePopover();

                    dispatch(
                      checkKillhouseRequestGuildService({
                        guilds_key: guild.key,
                        state: "accepted",
                        role: getRoleFromUrl(),
                      })
                    ).then((r) => {
                      if (r.payload.error) {
                        openNotif({
                          vertical: "top",
                          horizontal: "center",
                          msg: "مشکلی پیش آمده است!",
                          severity: "error",
                        });
                      } else {
                        updateTable();
                        openNotif({
                          vertical: "top",
                          horizontal: "center",
                          msg: "عملیات با موفقیت انجام شد.",
                          severity: "success",
                        });
                      }
                    });
                  }}
                >
                  تایید
                </Button>
                <Button
                  size="small"
                  color="error"
                  startIcon={<CloseIcon />}
                  sx={{ fontSize: { xs: 12, md: 15 } }}
                  onClick={() => {
                    closePopover();

                    dispatch(
                      OPEN_MODAL({
                        title: "رد درخواست ثبت صنف",
                        content: (
                          <RejectModal
                            guild={guild}
                            updateTable={updateTable}
                          />
                        ),
                      })
                    );
                  }}
                >
                  رد
                </Button>
              </Grid>
            ) : (
              <Grid
                container
                alignItems="flex-start"
                justifyContent="flex-start"
                gap={SPACING.TINY}
                direction="column"
              >
                <Button
                  size="small"
                  color="success"
                  startIcon={<CheckCircleIcon />}
                  sx={{ fontSize: { xs: 12, md: 15 } }}
                  onClick={() => {
                    closePopover();
                    dispatch(
                      OPEN_MODAL({
                        title: "ثبت کد احراز",
                        content: (
                          <ProvinceManageGuildsSubmitRegisterCode
                            item={guild}
                            updateTable={updateTable}
                          />
                        ),
                      })
                    );
                  }}
                >
                  ثبت کد احراز
                </Button>

                <Button
                  size="small"
                  color="secondary"
                  startIcon={<SendIcon />}
                  sx={{ fontSize: { xs: 12, md: 15 } }}
                  onClick={() => {
                    closePopover();

                    dispatch(
                      provinceResendRegisterCodeStateService({
                        key: guild.key,
                      })
                    ).then((r) => {
                      if (r.payload.error) {
                        openNotif({
                          vertical: "top",
                          horizontal: "center",
                          msg: r.payload.error,
                          severity: "error",
                        });
                      } else {
                        updateTable();
                        openNotif({
                          vertical: "top",
                          horizontal: "center",
                          msg: "کد با موفقیت ارسال شد.",
                          severity: "success",
                        });
                      }
                    });
                  }}
                >
                  ارسال مجدد کد
                </Button>
              </Grid>
            )}
          </Grid>
        </div>
      </Popover>
    </Grid>
  );
};

const RejectModal = ({ guild, updateTable }) => {
  const [openNotif] = useContext(AppContext);
  const [text, setText] = useState("");
  const dispatch = useDispatch();

  return (
    <Grid container gap={SPACING.TINY}>
      <TextField
        placeholder="دلیل رد درخواست..."
        value={text}
        onChange={(e) => setText(e.target.value)}
      />
      <Button
        fullWidth
        variant="contained"
        color="primary"
        disabled={!text}
        onClick={() => {
          dispatch(
            checkKillhouseRequestGuildService({
              guilds_key: guild.key,
              state: "rejected",
              message: text,
              role: getRoleFromUrl(),
            })
          ).then((r) => {
            if (r.payload.error) {
              openNotif({
                vertical: "top",
                horizontal: "center",
                msg: "مشکلی پیش آمده است!",
                severity: "error",
              });
            } else {
              openNotif({
                vertical: "top",
                horizontal: "center",
                msg: "عملیات با موفقیت انجام شد.",
                severity: "success",
              });
              updateTable();
              dispatch(CLOSE_MODAL());
            }
          });
        }}
      >
        ثبت
      </Button>
    </Grid>
  );
};
