import { Settings } from "@mui/icons-material";
import { IconButton, Menu, MenuItem } 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";

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 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 startCall = async () => {
    const newMeeting: NewMeeting = {
      startTime: "2022-03-30T23:40:00Z",
      duration: 30,
      topic: `Meeting with ${user.name}`,
      registrantIds: [user.uuid],
    };
    try {
      const response = await axios.post(
        `/users/${me}/meetings`,
        JSON.stringify(newMeeting)
      );
      window.open(response.data.joinUrl, "_blank")?.focus();
    } 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={() => {
              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>
    </div>
  );
};

export default SettingsButton;
