import {
  Avatar,
  ButtonBase,
  Divider,
  ListItemAvatar,
  ListItemIcon,
  ListItemText,
  Menu,
  MenuItem,
} from "@suid/material";
import { Show, createSignal, createUniqueId, type ParentComponent } from "solid-js";
import {
  Settings as SettingsIcon,
  Bookmark as BookmarkIcon,
  Star as LikeIcon,
  FeaturedPlayList as ListIcon,
} from "@suid/icons-material";

const ProfileMenuButton: ParentComponent<{
  profile?: { displayName: string; avatar: string; username: string };
  onClick?: () => void;
  onClose?: () => void;
}> = (props) => {
  const menuId = createUniqueId();
  const buttonId = createUniqueId();

  let [anchor, setAnchor] = createSignal<HTMLButtonElement | null>(null);
  const open = () => !!anchor();

  const onClick = (
    event: MouseEvent & { currentTarget: HTMLButtonElement },
  ) => {
    setAnchor(event.currentTarget);
    props.onClick?.();
  };

  const onClose = () => {
    props.onClick?.();
    setAnchor(null);
  };

  return (
    <>
      <ButtonBase
        aria-haspopup="true"
        sx={{ borderRadius: "50%" }}
        id={buttonId}
        onClick={onClick}
        aria-controls={open() ? menuId : undefined}
        aria-expanded={open() ? "true" : undefined}
      >
        <Avatar
          alt={`${props.profile?.displayName}'s avatar`}
          src={props.profile?.avatar}
        ></Avatar>
      </ButtonBase>
      <Menu
        id={menuId}
        anchorEl={anchor()}
        open={open()}
        onClose={onClose}
        MenuListProps={{
          "aria-labelledby": buttonId,
          sx: {
            minWidth: "220px",
          }
        }}
        anchorOrigin={{
          vertical: "top",
          horizontal: "right",
        }}
        transformOrigin={{
          vertical: "top",
          horizontal: "right",
        }}
      >
        <MenuItem>
          <ListItemAvatar>
            <Avatar src={props.profile?.avatar}></Avatar>
          </ListItemAvatar>
          <ListItemText
            primary={props.profile?.displayName}
            secondary={`@${props.profile?.username}`}
          ></ListItemText>
        </MenuItem>

        <MenuItem>
          <ListItemIcon>
            <BookmarkIcon />
          </ListItemIcon>
          <ListItemText>Bookmarks</ListItemText>
        </MenuItem>
        <MenuItem>
          <ListItemIcon>
            <LikeIcon />
          </ListItemIcon>
          <ListItemText>Likes</ListItemText>
        </MenuItem>
        <MenuItem>
          <ListItemIcon>
            <ListIcon />
          </ListItemIcon>
          <ListItemText>Lists</ListItemText>
        </MenuItem>
        <Divider />
        <Show when={props.children}>
          {props.children}
          <Divider />
        </Show>
        <MenuItem>
          <ListItemIcon>
            <SettingsIcon />
          </ListItemIcon>
          <ListItemText>Settings</ListItemText>
        </MenuItem>
      </Menu>
    </>
  );
};

export default ProfileMenuButton;
