import {
  Button,
  FormControlLabel,
  IconButton,
  Popover,
  Switch,
  Tooltip,
} from "@mui/material";
import EditIcon from "@mui/icons-material/Edit";
import { useContext, useState } from "react";
import { useDispatch } from "react-redux";
import axios from "axios";
import { Grid } from "../../../../components/grid/Grid";
import {
  DRAWER,
  OPEN_MODAL,
  LOADING_START,
  LOADING_END,
} from "../../../../lib/redux/slices/appSlice";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { CreateGuilds } from "../create-guilds/CreateGuilds";
import { GuildLimitaion } from "../guild-limitaion/GuildLimitaion";
import ManageHistoryIcon from "@mui/icons-material/ManageHistory";
import VisibilityIcon from "@mui/icons-material/Visibility";
import CheckCircleIcon from "@mui/icons-material/CheckCircle";
import SendIcon from "@mui/icons-material/Send";
import { AppContext } from "../../../../contexts/AppContext";
import { SPACING } from "../../../../data/spacing";
import { ProvinceManageGuildsSubmitRegisterCode } from "../province-manage-guilds-submit-register-code/ProvinceManageGuildsSubmitRegisterCode";
import { provinceResendRegisterCodeStateService } from "../../services/province-get-register-code-state";
import { ViewGuildDetails } from "../view-guild-details/ViewGuildDetails";
import TuneIcon from "@mui/icons-material/Tune";

export const ManageGuildsOperations = ({ guild, updateTable }) => {
  const dispatch = useDispatch();
  const [checked, setChecked] = useState(guild.active);
  const [popoverOpen, setPopoverOpen] = useState(false);
  const [anchorEl, setAnchorEl] = useState(null);
  const [openNotif] = useContext(AppContext);

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

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

  const handleChange = async (event) => {
    const newChecked = event.target.checked;
    setChecked(newChecked);

    dispatch(LOADING_START());

    try {
      const response = await axios.put("guilds/0/", {
        guilds_key: guild?.key,
        active: newChecked,
        role: getRoleFromUrl(),
      });

      dispatch(LOADING_END());

      if (response.status === 200) {
        updateTable();
        dispatch(DRAWER({ right: false, bottom: false, content: null }));
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: "عملیات با موفقیت انجام شد.",
          severity: "success",
        });
      }
    } catch (error) {
      dispatch(LOADING_END());
      const errorMessage =
        error.response?.data?.result ||
        error.response?.data?.error ||
        "خطا در انجام عملیات";
      openNotif({
        vertical: "top",
        horizontal: "center",
        msg: errorMessage,
        severity: "error",
      });
      // Revert the checkbox state on error
      setChecked(!newChecked);
    }
  };

  return (
    <Grid>
      <Tooltip title="مدیریت صنف" placement="left">
        <IconButton color="primary" onClick={openPopover}>
          <TuneIcon />
        </IconButton>
      </Tooltip>

      <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}
          >
            <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>

            {["AdminX", "SuperAdmin", "GuildRoom"].includes(
              getRoleFromUrl()
            ) && (
              <>
                <FormControlLabel
                  control={
                    <Switch
                      checked={checked}
                      onChange={handleChange}
                      color="primary"
                    />
                  }
                  label={checked ? "فعال" : "غیرفعال"}
                  style={{
                    justifyContent: "center",
                    alignItems: "center",
                    display: "flex",
                  }}
                />
                <Button
                  color="primary"
                  size="small"
                  startIcon={<EditIcon />}
                  sx={{ fontSize: { xs: 12, md: 15 } }}
                  // disabled={guild?.provinceAcceptState !== "pending"}
                  onClick={() => {
                    closePopover();
                    dispatch(
                      OPEN_MODAL({
                        right: !(window.innerWidth <= 600),
                        bottom: window.innerWidth <= 600,
                        title: "ویرایش واحد",
                        size: window.innerWidth <= 600 ? "small" : "auto",
                        content: (
                          <CreateGuilds
                            guild={guild}
                            updateTable={updateTable}
                          />
                        ),
                      })
                    );
                  }}
                >
                  ویرایش
                </Button>
                <Button
                  size="small"
                  color="warning"
                  startIcon={<ManageHistoryIcon />}
                  sx={{ fontSize: { xs: 12, md: 15 } }}
                  onClick={() => {
                    closePopover();
                    dispatch(
                      DRAWER({
                        right: !(window.innerWidth <= 600),
                        bottom: window.innerWidth <= 600,
                        title: "اعمال محدودیت",
                        content: (
                          <GuildLimitaion
                            guild={guild}
                            updateTable={updateTable}
                          />
                        ),
                      })
                    );
                  }}
                >
                  محدودیت
                </Button>
              </>
            )}

            {!guild?.isRegistered && (
              <Grid
                container
                alignItems="flex-start"
                justifyContent="flex-start"
                gap={SPACING.TINY}
                direction="column"
              >
                <Button
                  size="small"
                  color="success"
                  startIcon={<CheckCircleIcon size={30} />}
                  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>
  );
};
