import React from "react";
import {
  ListItemButton,
  ListItemIcon,
  ListItemText,
  Tooltip,
  Button,
  Grid,
} from "@mui/material";
import LogoutIcon from "@mui/icons-material/Logout";
import { useDispatch } from "react-redux";
import { LOG_OUT } from "../../../lib/redux/slices/userSlice";
import {
  BACKDROP_HIDE,
  CLOSE_MODAL,
  DRAWER,
  OPEN_MODAL,
} from "../../../lib/redux/slices/appSlice";
import { SPACING } from "../../../data/spacing";

export const LogoutButton = React.memo(({ open, onClose }) => {
  const dispatch = useDispatch();

  const handleLogout = () => {
    onClose();
    dispatch(DRAWER({ right: false, bottom: false, content: null }));
    dispatch(
      OPEN_MODAL({
        title: "از سامانه خارج میشوید؟",
        content: (
          <Grid container gap={SPACING.SMALL}>
            <Button
              color="error"
              variant="contained"
              onClick={() => {
                dispatch(BACKDROP_HIDE());
                onClose();
                dispatch(CLOSE_MODAL());
                dispatch(LOG_OUT());
              }}
            >
              بله
            </Button>
            <Button
              variant="outlined"
              onClick={() => {
                dispatch(CLOSE_MODAL());
              }}
            >
              خیر
            </Button>
          </Grid>
        ),
      })
    );
  };

  const content = (
    <ListItemButton onClick={handleLogout}>
      <ListItemIcon>
        <LogoutIcon color="primary" />
      </ListItemIcon>
      <ListItemText color="primary" primary="خروج" />
    </ListItemButton>
  );

  if (!open) {
    return (
      <Tooltip title="خروج" placement="left-start">
        {content}
      </Tooltip>
    );
  }

  return content;
});

LogoutButton.displayName = "LogoutButton";
