"use client";

import IconButton from "@mui/material/IconButton";
import Menu from "@mui/material/Menu";
import MenuItem from "@mui/material/MenuItem";
import Avatar from "@mui/material/Avatar";
import React from "react";
import { AppBarProps } from "./AppBar";
import Divider from "@mui/material/Divider";
import Typography from "@mui/material/Typography";
import { useTranslation } from "react-i18next";
import { signOut } from "next-auth/react";

type Props = Pick<AppBarProps, "avatarImageSrc" | "profileName">;

const Profile: React.FC<Props> = ({ avatarImageSrc, profileName }) => {
  const [profileMenuAnchorEl, setProfileMenuAnchorEl] =
    React.useState<HTMLButtonElement>();
  const openProfileMenu: React.MouseEventHandler<HTMLButtonElement> = (
    event,
  ) => {
    setProfileMenuAnchorEl(event.currentTarget);
  };
  const closeProfileMenu = () => {
    setProfileMenuAnchorEl(undefined);
  };

  const { t } = useTranslation("common");

  return (
    <>
      <IconButton aria-label={t("profile")} onClick={openProfileMenu}>
        <Avatar src={avatarImageSrc} />
      </IconButton>
      <Menu
        id="profile-menu"
        anchorEl={profileMenuAnchorEl}
        anchorOrigin={{ vertical: "bottom", horizontal: "right" }}
        transformOrigin={{ vertical: "top", horizontal: "right" }}
        keepMounted
        open={Boolean(profileMenuAnchorEl)}
        onClose={closeProfileMenu}
        MenuListProps={{
          dense: true,
          disablePadding: false,
          sx: { py: 0, minWidth: 180 },
        }}
        PaperProps={{ variant: "outlined" }}
      >
        <Typography sx={{ px: 2, py: 1.5, fontWeight: 600, color: "text.secondary", fontSize: "0.875rem" }}>
          {profileName}
        </Typography>
        <Divider />
        <MenuItem onClick={() => signOut()} sx={{ py: 1.5, fontSize: "0.875rem" }}>
          {t("Sign out")}
        </MenuItem>
      </Menu>
    </>
  );
};

export default Profile;
