import { mdiWhiteBalanceSunny } from "@mdi/js";
import Icon from "@mdi/react";
import SettingsIcon from "@mui/icons-material/Settings";
import { Button } from "@mui/material";
import AppBar from "@mui/material/AppBar";
import Menu from "@mui/material/Menu";
import MenuItem from "@mui/material/MenuItem";
import Toolbar from "@mui/material/Toolbar";
import Typography from "@mui/material/Typography";
import * as React from "react";
import { useAuthInfo } from "./BaseAuthenticatedPage";
import { DarkThemeButton } from "./DarkThemeButton";
import { RouterLink } from "./RouterLink";

export function SolarEnergyAppBar(p: {
  onSignOut: () => void;
}): React.ReactElement {
  const authInfo = useAuthInfo();

  const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null);
  const handleMenu = (event: React.MouseEvent<HTMLElement>) => {
    setAnchorEl(event.currentTarget);
  };

  const handleCloseMenu = () => {
    setAnchorEl(null);
  };

  const signOut = () => {
    handleCloseMenu();
    p.onSignOut();
  };

  return (
    <AppBar position="sticky">
      <Toolbar>
        <Icon
          path={mdiWhiteBalanceSunny}
          size={1}
          style={{ marginRight: "1rem" }}
        />

        <Typography variant="h6" component="div" sx={{ flexGrow: 1 }}>
          <RouterLink to="/">Solar Energy</RouterLink>
        </Typography>

        <div>
          <DarkThemeButton />

          <Button size="large" color="inherit">
            {authInfo!.info.id}
          </Button>

          <Button
            size="large"
            aria-label="account of current user"
            aria-controls="menu-appbar"
            aria-haspopup="true"
            onClick={handleMenu}
            color="inherit"
          >
            <SettingsIcon />
          </Button>
          <Menu
            id="menu-appbar"
            anchorEl={anchorEl}
            anchorOrigin={{
              vertical: "top",
              horizontal: "right",
            }}
            keepMounted
            transformOrigin={{
              vertical: "top",
              horizontal: "right",
            }}
            open={Boolean(anchorEl)}
            onClose={handleCloseMenu}
          >
            <MenuItem onClick={signOut}>Déconnexion</MenuItem>
          </Menu>
        </div>
      </Toolbar>
    </AppBar>
  );
}
