"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";
import { usePathname, useRouter, useSearchParams } from "next/navigation";

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, i18n: { language } } = useTranslation("login");
  const router = useRouter();
  const pathname = usePathname();
  const searchParams = useSearchParams()

  const onLangClick = React.useCallback((lang: string) => {
    const params = new URLSearchParams(searchParams.toString())
    params.set("lang", lang)
    router.replace(`${pathname}?${params.toString()}`);
    setTimeout(() => {
      window.location.reload();
    }, 80);
  }, [router, pathname, searchParams]);

  return (
    <>
      <IconButton aria-label="profile" onClick={openProfileMenu}>
        <Avatar src={avatarImageSrc} />
      </IconButton>
      <Menu
        id="profile-menu"
        anchorEl={profileMenuAnchorEl}
        anchorOrigin={{
          vertical: "bottom",
          horizontal: "right",
        }}
        keepMounted
        transformOrigin={{
          vertical: "top",
          horizontal: "right",
        }}
        open={Boolean(profileMenuAnchorEl)}
        onClose={closeProfileMenu}
        MenuListProps={{ dense: true, disablePadding: true }}
      >
        <Typography sx={{ mx: "1.5rem", my: "0.5rem" }} fontWeight="bold">
          {profileName}
        </Typography>
        <Divider />
        <MenuItem onClick={() => { router.replace("/changepassword") }}>{t("Change Password")}</MenuItem>
        {language === "zh" && <MenuItem onClick={() => { onLangClick("en") }}>{t("Change To English Version")}</MenuItem>}
        {language === "en" && <MenuItem onClick={() => { onLangClick("zh") }}>{t("Change To Chinese Version")}</MenuItem>}
        <MenuItem onClick={() => signOut()}>{t("Sign out")}</MenuItem>
      </Menu>
    </>
  );
};

export default Profile;
