import {
  Menu,
  MenuButton,
  MenuItem,
  MenuList,
  MenuPopover,
  MenuTrigger,
  makeStyles,
  typographyStyles,
} from "@fluentui/react-components";
import { ServerApi } from "./api/ServerApi";
import { AuthRouteWidget } from "./routes/AuthRouteWidget";
import { AsyncWidget } from "./widgets/AsyncWidget";
import { AuthApi } from "./api/AuthApi";
import { useAlert } from "./hooks/providers/AlertDialogProvider";
import { useConfirm } from "./hooks/providers/ConfirmDialogProvider";

const useStyles = makeStyles({
  title: typographyStyles.title2,
});

export function App() {
  return (
    <AsyncWidget
      loadKey={1}
      errMsg="Failed to load server configuration!"
      load={ServerApi.LoadConfig}
      loadingMessage="Loading server configuration..."
      build={() => <AppInner />}
    />
  );
}

function AppInner(): React.ReactElement {
  const alert = useAlert();
  const confirm = useConfirm();
  const styles = useStyles();

  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!");
    }
  };

  if (!ServerApi.Config.authenticated && !ServerApi.Config.disable_auth)
    return <AuthRouteWidget />;

  return (
    <div
      style={{
        width: "100%",
        maxWidth: "1000px",
        margin: "50px auto",
      }}
    >
      <div style={{ display: "flex", justifyContent: "space-between" }}>
        <span className={styles.title}>VirtWebRemote</span>
        <Menu>
          <MenuTrigger disableButtonEnhancement>
            <MenuButton>Account</MenuButton>
          </MenuTrigger>

          <MenuPopover>
            <MenuList>
              <MenuItem onClick={signOut}>Sign out</MenuItem>
            </MenuList>
          </MenuPopover>
        </Menu>
      </div>
    </div>
  );
}
