import {
  Collapse,
  Divider,
  Drawer,
  List,
  ListItemButton,
  ListItemText,
  Toolbar,
} from "@mui/material";
import React from "react";
import { ExpandLess, ExpandMore } from "@mui/icons-material";
import ContactItem from "./sidebar-components/ContactItem";
import { useAppSelector } from "../../../redux/hooks";
import { selectUsers, selectTeam } from "../../../redux/slices/usersSlice";
import { selectFavorites } from "../../../redux/slices/favoritesSlice";
import UserLite from "../../../api-bodies/UserLite";

interface Props {
  setContactSelected: (contactInfo: UserLite) => void;
}

const sidebarWidth = 240;

const Sidebar: React.FC<Props> = (props) => {
  const [favoritesOpen, setFavoritesOpen] = React.useState<boolean>(true);
  const [teamOpen, setTeamOpen] = React.useState<boolean>(false);

  const favoritesUuids = useAppSelector(selectFavorites);
  const favorites = useAppSelector((state) =>
    selectUsers(state, favoritesUuids)
  );
  const team = useAppSelector(selectTeam);

  return (
    <Drawer
      variant="permanent"
      sx={{
        width: sidebarWidth,
        ["& .MuiDrawer-paper"]: { width: sidebarWidth },
      }}
    >
      <Toolbar />
      <List>
        <ListItemText
          primary="Contacts"
          primaryTypographyProps={{ variant: "h6" }}
          sx={{ textAlign: "center" }}
        />
        <Divider />
        <ListItemButton onClick={() => setFavoritesOpen(!favoritesOpen)}>
          {favoritesOpen ? <ExpandLess /> : <ExpandMore />}
          <ListItemText primary="Favorites" sx={{ textAlign: "center" }} />
          <ListItemText
            primary={favorites.length}
            sx={{ textAlign: "right" }}
          />
        </ListItemButton>
        <Collapse in={favoritesOpen} timeout="auto" unmountOnExit>
          <List disablePadding>
            {favorites.map((favorite, i) => (
              <ContactItem
                contactInfo={favorite}
                key={i}
                setContactSelected={props.setContactSelected}
              />
            ))}
          </List>
        </Collapse>
        <ListItemButton onClick={() => setTeamOpen(!teamOpen)}>
          {teamOpen ? <ExpandLess /> : <ExpandMore />}
          <ListItemText primary="Team" sx={{ textAlign: "center" }} />
          <ListItemText primary={team.length} sx={{ textAlign: "right" }} />
        </ListItemButton>
        <Collapse in={teamOpen} timeout="auto" unmountOnExit>
          <List disablePadding>
            {team.map((member, i) => (
              <ContactItem
                contactInfo={member}
                key={i}
                setContactSelected={props.setContactSelected}
              />
            ))}
          </List>
        </Collapse>
      </List>
    </Drawer>
  );
};

export default Sidebar;
