import { Settings } from "@mui/icons-material";
import { Alert, IconButton, Menu, MenuItem, Snackbar } from "@mui/material";
import { useState } from "react";
import UserLite from "../../api-bodies/UserLite";
import UserStatus from "../../api-bodies/UserStatus";
import { useAppDispatch, useAppSelector } from "../../redux/hooks";
import {
  selectFavorites,
  addFavorite,
  removeFavorite,
} from "../../redux/slices/favoritesSlice";
import { open as openMeetingDetails } from "../../redux/slices/meetingDetailsOpenSlice";
import { selectMeeting } from "../../redux/slices/meetingsAndUserStatusSlice";
import { useNavigate } from "react-router-dom";
import { selectMe } from "../../redux/slices/usersSlice";
import NewMeeting from "../../api-bodies/NewMeeting";
import axios from "../../api/axios";
import { open as openMeetingUrl } from "../../redux/slices/meetingUrlSlice";

interface Props {
  user: UserLite;
  status: UserStatus;
}

const SettingsButton: React.FC<Props> = ({ user, status }: Props) => {
  const navigate = useNavigate();
  const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null);
  const [snackbarOpen, setSnackbarOpen] = useState(false);
  const me = useAppSelector(selectMe);
  const favoritesUuids = useAppSelector(selectFavorites);
  const meeting = useAppSelector((state) =>
    selectMeeting(state, status.meetingId)
  );
  const dispatch = useAppDispatch();
  const open = Boolean(anchorEl);
  const handleClick = (event: React.MouseEvent<HTMLButtonElement>) => {
    setAnchorEl(event.currentTarget);
  };
  const handleClose = () => {
    setAnchorEl(null);
  };
  const handleSnackbarClose = (
    event?: React.SyntheticEvent | Event,
    reason?: string
  ) => {
    if (reason === "clickaway") {
      return;
    }
    setSnackbarOpen(false);
  };

  const startCall = async () => {
    const start = new Date().toISOString();
    let newStart = start.split(".")[0];
    newStart += start.includes("Z") ? "Z" : "";
    const newMeeting: NewMeeting = {
      startTime: newStart,
      duration: 30,
      topic: `Meeting with ${user.name}`,
      registrantIds: [user.uuid, me],
    };
    try {
      const response = await axios.post(
        `/users/${me}/meetings`,
        JSON.stringify(newMeeting)
      );
      dispatch(openMeetingUrl(response.data.joinUrl));
    } catch (e) {
      console.log(e);
    }
  };

  return (
    <div>
      <IconButton
        sx={{ position: "absolute", right: 0 }}
        aria-controls={open ? "context-menu" : undefined}
        aria-haspopup="true"
        aria-expanded={open ? "true" : undefined}
        onClick={handleClick}
      >
        <Settings />
      </IconButton>
      <Menu
        id="context-menu"
        anchorEl={anchorEl}
        open={open}
        onClose={handleClose}
        MenuListProps={{ "aria-labelledby": "basic-button" }}
      >
        {favoritesUuids.includes(user.uuid) ? (
          <MenuItem
            onClick={() => {
              handleClose();
              dispatch(removeFavorite({ userId: me, toBeRemoved: user.uuid }));
            }}
          >
            Remove from Favorites
          </MenuItem>
        ) : (
          <MenuItem
            onClick={() => {
              setSnackbarOpen(true);
              handleClose();
              dispatch(addFavorite({ userId: me, toBeAdded: user.uuid }));
            }}
          >
            Add to Favorites
          </MenuItem>
        )}
        {status.inMeeting ? (
          <MenuItem
            onClick={() => {
              handleClose();
              dispatch(openMeetingDetails(meeting));
            }}
          >
            View current meeting
          </MenuItem>
        ) : null}
        <MenuItem
          onClick={() => {
            handleClose();
            navigate(`../contacts/${user.uuid}`);
          }}
        >
          View upcoming meetings
        </MenuItem>
        <MenuItem
          onClick={() => {
            handleClose();
            startCall();
          }}
        >
          Create meeting
        </MenuItem>
      </Menu>
      <Snackbar
        anchorOrigin={{ vertical: "bottom", horizontal: "right" }}
        open={snackbarOpen}
        autoHideDuration={3000}
        onClose={handleSnackbarClose}
      >
        <Alert
          onClose={handleSnackbarClose}
          severity="success"
          sx={{ width: "100%" }}
        >
          User successfully added to favourites list!
        </Alert>
      </Snackbar>
    </div>
  );
};

export default SettingsButton;
