import type { LinkButtonProps } from '@/components/LinkButton'
import LinkButton from '@/components/LinkButton'
import { ButtonGroup, Classes, Colors, Divider } from '@blueprintjs/core'
import { css, cx } from '@emotion/css'
import useAuthIdentity from '@inject/graphql/auth'
import responsiveButtonGroup from '@inject/shared/css/responsiveButtonGroup'
import NotificationDropdown from '@inject/shared/notification/NotificationDropdown'
import type { FC, PropsWithChildren } from 'react'
import { useMemo } from 'react'
import UserTitle from './UserTitle'

const wrapper = css`
  height: 100%;
  display: flex;
  flex-direction: column;
`

const outlet = css`
  flex: 1;
  overflow: auto;

  // make sure the navbar doesn't cover any toggles
  @media (min-width: 40rem) {
    padding-bottom: 3rem;
  }
`

const navbar = css`
  position: fixed;
  bottom: 0;
  right: 0;
  // appear on top of buttons
  z-index: 11;

  width: max-content;
  max-width: 100vw;
  margin-left: auto;
  padding: 0.5rem;

  display: flex;
  justify-content: right;
  gap: 1rem;
  flex-grow: 0;

  white-space: nowrap;

  @media (max-width: 50rem) {
    position: static;
    border-left: 0;
    justify-content: center;
    width: 100%;
  }

  border: 1px solid rgba(17, 20, 24, 0.15);
  border-right: 0;
  border-bottom: 0;

  background-color: ${Colors.WHITE};
  .${Classes.DARK} & {
    background-color: ${Colors.DARK_GRAY3};
    border-color: rgba(255, 255, 255, 0.15);
  }
`

const superuserLinks: LinkButtonProps[] = [
  {
    link: ['/exercise-panel'],
    button: {
      icon: 'torch',
      text: 'Exercise panel',
      title: 'Exercise panel',
      minimal: true,
    },
  },
  {
    link: ['/users'],
    button: {
      icon: 'people',
      text: 'Users',
      title: 'Users',
      minimal: true,
    },
  },
]

const Navbar: FC<PropsWithChildren> = ({ children }) => {
  const { whoAmI, isStaff, isSuperuser } = useAuthIdentity()

  const links = useMemo<LinkButtonProps[]>(
    () => [
      {
        link: ['/'],
        button: {
          icon: 'home',
          text: 'Home',
          title: 'Home',
          minimal: true,
        },
        end: true,
      },
      ...(isStaff || isSuperuser ? superuserLinks : []),
      {
        link: ['/settings'],
        button: {
          icon: 'cog',
          text: 'Settings',
          title: 'Settings',
          minimal: true,
        },
      },
    ],
    [isStaff, isSuperuser]
  )

  return (
    <div className={wrapper}>
      <div className={outlet}>{children}</div>
      <div className={cx(navbar, responsiveButtonGroup)}>
        <ButtonGroup>
          {links.map(child => (
            <LinkButton key={child.link?.[0].toString()} {...child} />
          ))}
          <Divider />
          <NotificationDropdown placement='top' hideLabel />
        </ButtonGroup>
        {whoAmI?.username && <UserTitle username={whoAmI.username} />}
      </div>
    </div>
  )
}

export default Navbar
