import { useContext, useState } from "react";
import { useDispatch } from "react-redux";
import {
  Box,
  Grid,
  IconButton,
  List,
  ListItemButton,
  ListItemIcon,
  ListItemText,
  Popover,
  Typography,
  Button,
} from "@mui/material";
import TuneIcon from "@mui/icons-material/Tune";
import PersonAddAlt1RoundedIcon from "@mui/icons-material/PersonAddAlt1Rounded";
import AddIcon from "@mui/icons-material/Add";
import EditIcon from "@mui/icons-material/Edit";
import DeleteIcon from "@mui/icons-material/Delete";
import { AppContext } from "../../../../contexts/AppContext";
import {
  LOADING_START,
  LOADING_END,
  CLOSE_MODAL,
  OPEN_MODAL,
} from "../../../../lib/redux/slices/appSlice";
import axios from "axios";
import { getFaUserRole } from "../../../../utils/getFaUserRole";
import { AssignSubUserModal } from "./AssignSubUserModal";
import { AddAccessLevelModal } from "./AddAccessLevelModal";
import { EditSubSectionsModal } from "./EditSubSectionsModal";

export const DeviceOperations = ({
  device,
  onSubUserAssigned,
  fetchApiData,
  page,
}) => {
  const [anchorEl, setAnchorEl] = useState(null);
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);

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

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

  const handleAssignSubUser = () => {
    handleClose();
    dispatch(
      OPEN_MODAL({
        title: "اختصاص دستگاه به کاربر فرعی",
        width: "auto",
        content: (
          <AssignSubUserModal device={device} onSuccess={onSubUserAssigned} />
        ),
      })
    );
  };

  const handleAddAccessLevel = () => {
    handleClose();
    dispatch(
      OPEN_MODAL({
        title: "افزودن سطح دسترسی",
        width: "auto",
        content: (
          <AddAccessLevelModal device={device} onSuccess={onSubUserAssigned} />
        ),
      })
    );
  };

  const handleEditSubSections = (accessLevel) => {
    handleClose();
    dispatch(
      OPEN_MODAL({
        title: "ویرایش زیربخش‌های سطح دسترسی",
        width: "auto",
        content: (
          <EditSubSectionsModal
            accessLevel={accessLevel}
            device={device}
            onSuccess={() => fetchApiData(page)}
          />
        ),
      })
    );
  };

  const handleDeleteAccessLevel = (accessLevel) => {
    handleClose();
    dispatch(
      OPEN_MODAL({
        title: "حذف سطح دسترسی",
        size: 320,
        content: (
          <Grid container spacing={2}>
            <Grid
              item
              xs={12}
              container
              justifyContent="center"
              alignItems="center"
              mb={2}
            >
              <Typography variant="body2" color="default">
                آیا از حذف سطح دسترسی{" "}
                {getFaUserRole(accessLevel?.name) || accessLevel?.name} مطمئن
                هستید؟
              </Typography>
            </Grid>
            <Grid item xs={6}>
              <Button
                fullWidth
                variant="contained"
                color="error"
                onClick={async () => {
                  try {
                    dispatch(LOADING_START());
                    await axios.delete(
                      `/pos-access-level/0/?key=${accessLevel?.key}`
                    );
                    dispatch(LOADING_END());
                    dispatch(CLOSE_MODAL());
                    openNotif({
                      vertical: "top",
                      horizontal: "center",
                      severity: "success",
                      msg: "سطح دسترسی با موفقیت حذف شد.",
                    });
                    if (fetchApiData) {
                      fetchApiData(page);
                    }
                  } catch (error) {
                    dispatch(LOADING_END());
                    openNotif({
                      vertical: "top",
                      horizontal: "center",
                      severity: "error",
                      msg:
                        error?.response?.data?.result ||
                        error?.response?.data?.detail ||
                        "حذف سطح دسترسی با خطا مواجه شد.",
                    });
                  }
                }}
              >
                تایید
              </Button>
            </Grid>
            <Grid item xs={6}>
              <Button
                fullWidth
                variant="outlined"
                onClick={() => dispatch(CLOSE_MODAL())}
              >
                انصراف
              </Button>
            </Grid>
          </Grid>
        ),
      })
    );
  };

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

  const accessLevels = Array.isArray(device?.accessLevels)
    ? device.accessLevels.filter((level) => !level?.trash)
    : [];

  return (
    <>
      <IconButton
        aria-describedby={id}
        color="primary"
        onClick={handleOpen}
        size="small"
      >
        <TuneIcon fontSize="small" />
      </IconButton>
      <Popover
        id={id}
        open={open}
        anchorEl={anchorEl}
        onClose={handleClose}
        anchorOrigin={{
          vertical: "bottom",
          horizontal: "right",
        }}
        transformOrigin={{
          vertical: "top",
          horizontal: "left",
        }}
      >
        <List sx={{ minWidth: 200, p: 0 }}>
          <ListItemButton onClick={handleAssignSubUser}>
            <ListItemIcon sx={{ minWidth: 36, color: "success.main" }}>
              <PersonAddAlt1RoundedIcon fontSize="small" />
            </ListItemIcon>
            <ListItemText
              primary="اختصاص به کاربر"
              primaryTypographyProps={{
                sx: { color: "success.main", fontSize: "0.875rem" },
              }}
            />
          </ListItemButton>
          <ListItemButton onClick={handleAddAccessLevel}>
            <ListItemIcon sx={{ minWidth: 36, color: "info.main" }}>
              <AddIcon fontSize="small" />
            </ListItemIcon>
            <ListItemText
              primary="افزودن سطح دسترسی"
              primaryTypographyProps={{
                sx: { color: "info.main", fontSize: "0.875rem" },
              }}
            />
          </ListItemButton>
          {accessLevels.length > 0 && (
            <>
              <Box sx={{ pl: 1.5, py: 0.5, bgcolor: "action.hover" }}>
                <Typography variant="caption" color="text.secondary">
                  مدیریت سطح دسترسی:
                </Typography>
              </Box>
              {accessLevels.map((level, idx) => (
                <Box key={level?.key || idx} sx={{ pl: 1, pr: 0.5 }}>
                  <Grid
                    container
                    alignItems="center"
                    justifyContent="space-between"
                  >
                    <Typography variant="body2" sx={{ py: 0.5, pl: 0.5 }}>
                      {getFaUserRole(level?.name) || level?.name || "-"}
                    </Typography>
                    <Grid gap={0.5}>
                      <IconButton
                        size="small"
                        color="primary"
                        onClick={() => handleEditSubSections(level)}
                      >
                        <EditIcon fontSize="small" />
                      </IconButton>
                      <IconButton
                        size="small"
                        color="error"
                        onClick={() => handleDeleteAccessLevel(level)}
                      >
                        <DeleteIcon fontSize="small" />
                      </IconButton>
                    </Grid>
                  </Grid>
                </Box>
              ))}
            </>
          )}
        </List>
      </Popover>
    </>
  );
};
