import { Box, Button, IconButton, Typography } from "@mui/material";
import React from "react";
import PhoneIcon from "@mui/icons-material/Phone";
import AddIcon from "@mui/icons-material/Add";
import UserLite from "../../../../api-bodies/UserLite";
import UserStatus from "../../../../api-bodies/UserStatus";
import { useAppSelector, useAppDispatch } from "../../../../redux/hooks";
import {
  selectUserStatus,
  selectMeeting,
} from "../../../../redux/slices/meetingsAndUserStatusSlice";
import {
  selectFavorites,
  addFavorite,
  removeFavorite,
} from "../../../../redux/slices/favoritesSlice";
import RemoveIcon from "@mui/icons-material/Remove";
import { MeetingStatus } from "../../../../utils";
import { selectManager, selectMe } from "../../../../redux/slices/usersSlice";
import axios from "../../../../api/axios";
import NewMeeting from "../../../../api-bodies/NewMeeting";

interface Props {
  contactInfo: UserLite;
}

const UpperBody: React.FC<Props> = ({ contactInfo }) => {
  const dispatch = useAppDispatch();
  const userStatus: UserStatus = useAppSelector((state) =>
    selectUserStatus(state, contactInfo.uuid)
  );
  const me = useAppSelector(selectMe);
  const favoritesUuids = useAppSelector(selectFavorites);
  const detailedMeeting = useAppSelector((state) =>
    selectMeeting(state, userStatus.inMeeting ? userStatus.meetingId : null)
  );
  const managerId = useAppSelector(selectManager);
  const meetingStatus: MeetingStatus =
    managerId === contactInfo.uuid
      ? MeetingStatus.NOT_AVAILABLE
      : userStatus && userStatus.inMeeting
        ? MeetingStatus.IN_MEETING
        : MeetingStatus.NOT_IN_MEETING;

  const startCall = async () => {
    const newMeeting: NewMeeting = {
      startTime: "2022-03-30T23:40:00Z",
      duration: 30,
      topic: `Meeting with ${contactInfo.name}`,
      registrantIds: [contactInfo.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 (
    <Box
      sx={{
        display: "flex",
        flexDirection: "column",
        border: 1,
        borderRadius: 2,
        borderColor: "#af000d",
        width: "70%",
        alignSelf: "center",
        mb: 2,
      }}
    >
      <Box
        sx={{
          display: "flex",
          flexDirection: "row",
          justifyContent: "space-between",
          alignItems: "center",
          mx: 4,
        }}
      >
        <Typography sx={{ mt: 2 }} variant="h3">{contactInfo.name}</Typography>
        {!favoritesUuids.includes(contactInfo.uuid) ? (
          <Button
            variant="contained"
            color="success"
            startIcon={<AddIcon />}
            onClick={() =>
              dispatch(addFavorite({ userId: me, toBeAdded: contactInfo.uuid }))
            }
          >
            favorites
          </Button>
        ) : (
          <Button
            variant="contained"
            color="secondary"
            startIcon={<RemoveIcon />}
            onClick={() =>
              dispatch(
                removeFavorite({
                  userId: me,
                  toBeRemoved: contactInfo.uuid,
                })
              )
            }
          >
            favorites
          </Button>
        )}
      </Box>
      <Box
        sx={{
          display: "flex",
          flexDirection: "row",
          alignItems: "center",
          justifyContent: "space-between",
          my: 2,
          mx: 4,
        }}
      >
        <Box>
          <IconButton
            sx={{ border: 1, backgroundColor: "white", mr: 1 }}
            size="large"
            color="secondary"
            onClick={startCall}
          >
            <PhoneIcon fontSize="large" />
          </IconButton>
        </Box>
        <Box sx={{ display: "flex", flexDirection: "column" }}>
          <Typography variant="button" sx={{ textAlign: "right" }}>
            {meetingStatus}
          </Typography>
          {detailedMeeting ? (
            <Typography variant="h6">{detailedMeeting.topic}</Typography>
          ) : null}
        </Box>
      </Box>
    </Box>
  );
};

export default UpperBody;
