import {
  Menu,
  MenuButton,
  MenuItem,
  MenuList,
  MenuPopover,
  MenuTrigger,
} from "@fluentui/react-components";
import { Checkmark12Regular } from "@fluentui/react-icons";
import { AuthApi } from "./../api/AuthApi";
import { useAlert } from "./../hooks/providers/AlertDialogProvider";
import { useConfirm } from "./../hooks/providers/ConfirmDialogProvider";
import { Theme, useTheme } from "./../hooks/providers/ThemeProvider";

export function MainMenu(): React.ReactElement {
  const alert = useAlert();
  const confirm = useConfirm();

  const signOut = async () => {
    try {
      if (!(await confirm("Do you really want to sign out?"))) return;
      await AuthApi.SignOut();
    } catch (e) {
      console.error(e);
      alert("Failed to perform sign out!");
    }
  };
  return (
    <Menu>
      <MenuTrigger disableButtonEnhancement>
        <MenuButton>Settings</MenuButton>
      </MenuTrigger>

      <MenuPopover>
        <MenuList>
          <Menu>
            <MenuTrigger disableButtonEnhancement>
              <MenuItem>Theme</MenuItem>
            </MenuTrigger>

            <MenuPopover>
              <MenuList>
                <ThemeMenuItem label="Teams Light" value="teamslight" />
                <ThemeMenuItem label="Teams Dark" value="teamsdark" />
                <ThemeMenuItem label="Web Light" value="weblight" />
                <ThemeMenuItem label="Web Dark" value="webdark" />
                <ThemeMenuItem label="High contrast" value="highcontrast" />
              </MenuList>
            </MenuPopover>
          </Menu>
          <MenuItem onClick={signOut}>Sign out</MenuItem>
        </MenuList>
      </MenuPopover>
    </Menu>
  );
}

function ThemeMenuItem(p: { label: string; value: Theme }): React.ReactElement {
  const theme = useTheme();

  return (
    <MenuItem
      icon={theme.theme === p.value ? <Checkmark12Regular /> : undefined}
      onClick={() => theme.set(p.value)}
    >
      {p.label}
    </MenuItem>
  );
}
