import {
  Button,
  FormControlLabel,
  IconButton,
  Popover,
  Switch,
  Tooltip,
  Typography,
  Box,
} from "@mui/material";
import EditIcon from "@mui/icons-material/Edit";
import DeleteIcon from "@mui/icons-material/Delete";
import { useContext, useState } from "react";
import { useDispatch } from "react-redux";
import { Grid } from "../../../../components/grid/Grid";
import {
  OPEN_MODAL,
  CLOSE_MODAL,
  LOADING_END,
  LOADING_START,
  DRAWER,
} from "../../../../lib/redux/slices/appSlice";
import { ProvinceLegalGuildsForm } from "./ProvinceLegalGuildsForm";
import TuneIcon from "@mui/icons-material/Tune";
import { AppContext } from "../../../../contexts/AppContext";
import { updateStewardService } from "../../services/update-steward";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import axios from "axios";

export const ProvinceLegalGuildsOperations = ({
  item,
  updateTable,
  userType,
}) => {
  const IS_STEWARD = userType === "steward";
  const dispatch = useDispatch();
  const [checked, setChecked] = useState(item?.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 handleActivationChange = async (event) => {
    const newChecked = event.target.checked;
    setChecked(newChecked);
    dispatch(LOADING_START());
    try {
      let response = null;
      if (IS_STEWARD) {
        response = await dispatch(
          updateStewardService({
            params: {
              id: item?.id,
            },
            body: {
              active: newChecked,
              role: getRoleFromUrl(),
            },
          })
        ).then(() => {
          updateTable();
          dispatch(DRAWER({ right: false, bottom: false, content: null }));
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: "عملیات با موفقیت انجام شد.",
            severity: "success",
          });
        });
      } else {
        response = await axios.put("guilds/0/", {
          guilds_key: item?.key,
          active: newChecked,
          role: getRoleFromUrl(),
        });
        if (response.status === 200) {
          updateTable();
          dispatch(DRAWER({ right: false, bottom: false, content: null }));
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: "عملیات با موفقیت انجام شد.",
            severity: "success",
          });
        }
      }

      dispatch(LOADING_END());
    } 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);
    }
  };

  const handleDelete = () => {
    closePopover();
    dispatch(
      OPEN_MODAL({
        title: "تایید حذف",
        size: "auto",
        content: (
          <Box sx={{ p: 2, minWidth: 300 }}>
            <Typography sx={{ mb: 3 }}>
              {`آیا از حذف این ${
                IS_STEWARD ? "مباشر" : "صنف"
              } حقوقی اطمینان دارید؟`}
            </Typography>
            <Grid container direction="row" justifyContent="space-between">
              <Button
                variant="outlined"
                onClick={() => dispatch(CLOSE_MODAL())}
                sx={{ width: "48%" }}
              >
                انصراف
              </Button>
              <Button
                variant="contained"
                color="error"
                onClick={() => {
                  if (IS_STEWARD) {
                    dispatch(
                      updateStewardService({
                        params: {
                          id: item?.id,
                        },
                        body: {
                          active: false,
                          trash: true,
                          role: getRoleFromUrl(),
                        },
                      })
                    )
                      .then(() => {
                        updateTable();
                        openNotif({
                          vertical: "top",
                          horizontal: "center",
                          msg: "عملیات حذف با موفقیت انجام شد.",
                          severity: "error",
                        });
                      })
                      .catch((error) => {
                        const errorMessage =
                          error.response?.data?.result ||
                          error.response?.data?.error ||
                          "خطا در انجام عملیات";
                        openNotif({
                          vertical: "top",
                          horizontal: "center",
                          msg: errorMessage,
                          severity: "error",
                        });
                      });
                  }
                  dispatch(CLOSE_MODAL());
                }}
                sx={{ width: "48%" }}
              >
                حذف
              </Button>
            </Grid>
          </Box>
        ),
      })
    );
  };

  const handleEdit = () => {
    closePopover();
    dispatch(
      OPEN_MODAL({
        title: `ویرایش ${IS_STEWARD ? "مباشر" : "صنف"} حقوقی`,
        content: (
          <ProvinceLegalGuildsForm
            item={item}
            onClose={() => dispatch(CLOSE_MODAL())}
            updateTable={updateTable}
            userType={userType}
          />
        ),
        size: window.innerWidth <= 600 ? "small" : "auto",
      })
    );
  };

  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, width: 120 }}>
          <Grid
            container
            direction="column"
            alignItems="flex-start"
            justifyContent="center"
            gap={1}
          >
            <FormControlLabel
              control={
                <Switch
                  checked={checked}
                  onChange={handleActivationChange}
                  color="primary"
                />
              }
              label={checked ? "فعال" : "غیرفعال"}
              style={{
                justifyContent: "center",
                alignItems: "center",
                display: "flex",
              }}
            />
            <Button
              color="primary"
              size="small"
              startIcon={<EditIcon />}
              sx={{ fontSize: { xs: 12, md: 15 } }}
              onClick={handleEdit}
            >
              ویرایش
            </Button>
            <Button
              size="small"
              color="error"
              startIcon={<DeleteIcon />}
              sx={{ fontSize: { xs: 12, md: 15 } }}
              onClick={handleDelete}
            >
              حذف
            </Button>
          </Grid>
        </div>
      </Popover>
    </Grid>
  );
};
