import {
  AppBar as AppBarMui,
  Box,
  Button,
  Menu,
  MenuItem,
  Toolbar,
  Typography
} from '@mui/material'

import { useEffect, useState } from 'react'
import { useAppSelector } from '../../hooks/store'
import Username from '../username'

import { Link, useNavigate } from 'react-router-dom'
import {
  appPublicRoutes,
  appPrivateRoutes,
  getProfileRoute
} from '../../routes'
import { getProfileUsername, hexToNpub } from '../../utils'
import styles from './style.module.scss'
import { Container } from '../Container'
import { ButtonIcon } from '../ButtonIcon'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faClose } from '@fortawesome/free-solid-svg-icons'
import useMediaQuery from '@mui/material/useMediaQuery'
import { useLogout } from '../../hooks/useLogout'

import { launch as launchNostrLoginDialog } from 'nostr-login'

export const AppBar = () => {
  const navigate = useNavigate()
  const logout = useLogout()
  const [username, setUsername] = useState('')
  const [userAvatar, setUserAvatar] = useState('')
  const [anchorElUser, setAnchorElUser] = useState<null | HTMLElement>(null)

  const authState = useAppSelector((state) => state.auth)
  const metadataState = useAppSelector((state) => state.metadata)
  const userRobotImage = useAppSelector((state) => state.userRobotImage)

  useEffect(() => {
    if (metadataState) {
      if (metadataState.content) {
        const profileMetadata = JSON.parse(metadataState.content)
        const { picture } = profileMetadata

        if (picture || userRobotImage) {
          setUserAvatar(picture || userRobotImage)
        }

        const npub = authState.usersPubkey
          ? hexToNpub(authState.usersPubkey)
          : ''

        setUsername(getProfileUsername(npub, profileMetadata))
      } else {
        setUserAvatar(userRobotImage || '')
        setUsername('')
      }
    }
  }, [metadataState, userRobotImage, authState.usersPubkey])

  const handleOpenUserMenu = (event: React.MouseEvent<HTMLElement>) => {
    setAnchorElUser(event.currentTarget)
  }

  const handleCloseUserMenu = () => {
    setAnchorElUser(null)
  }

  const handleProfile = () => {
    const hexKey = authState?.usersPubkey
    if (hexKey) navigate(getProfileRoute(hexKey))

    setAnchorElUser(null)
  }

  const handleLogout = () => {
    handleCloseUserMenu()
    logout()
    navigate('/')
  }
  const isAuthenticated = authState?.loggedIn === true

  const matches = useMediaQuery('(max-width:767px)')
  const [isBannerVisible, setIsBannerVisible] = useState(true)
  const handleBannerHide = () => {
    setIsBannerVisible(false)
  }

  return (
    <>
      {isAuthenticated && isBannerVisible && (
        <div className={styles.banner}>
          <Container>
            <div className={styles.bannerInner}>
              <p className={styles.bannerText}>
                SIGit is currently Beta software (available for user experience
                testing), use at your own risk!
              </p>
              <Button
                aria-label={`close banner`}
                variant="text"
                onClick={handleBannerHide}
              >
                <FontAwesomeIcon icon={faClose} />
              </Button>
            </div>
          </Container>
        </div>
      )}
      <AppBarMui
        position={matches ? 'sticky' : 'static'}
        className={styles.AppBar}
        sx={{
          boxShadow: 'none'
        }}
      >
        <Container>
          <Toolbar className={styles.toolbar} disableGutters={true}>
            <Box className={styles.logoWrapper}>
              <img
                src="/logo.svg"
                alt="Logo"
                onClick={() => {
                  if (window.location.pathname === '/') {
                    location.reload()
                  } else {
                    navigate('/')
                  }
                }}
              />
            </Box>

            <Box className={styles.rightSideBox}>
              {!isAuthenticated && (
                <Button
                  startIcon={<ButtonIcon />}
                  onClick={() => {
                    launchNostrLoginDialog()
                  }}
                  variant="contained"
                >
                  LOGIN
                </Button>
              )}

              {isAuthenticated && (
                <>
                  <Username
                    username={username}
                    avatarContent={userAvatar}
                    handleClick={handleOpenUserMenu}
                  />
                  <Menu
                    id="menu-appbar"
                    anchorEl={anchorElUser}
                    anchorOrigin={{
                      vertical: 'bottom',
                      horizontal: 'center'
                    }}
                    keepMounted
                    transformOrigin={{
                      vertical: 'top',
                      horizontal: 'center'
                    }}
                    open={!!anchorElUser}
                    onClose={handleCloseUserMenu}
                  >
                    <MenuItem
                      sx={{
                        justifyContent: 'center',
                        display: { md: 'none' },
                        fontWeight: 500,
                        fontSize: '14px',
                        color: 'var(--text-color)'
                      }}
                    >
                      <Typography variant="h6">{username}</Typography>
                    </MenuItem>
                    <MenuItem
                      onClick={handleProfile}
                      sx={{
                        justifyContent: 'center'
                      }}
                    >
                      Profile
                    </MenuItem>
                    <MenuItem
                      onClick={() => {
                        setAnchorElUser(null)

                        navigate(appPrivateRoutes.settings)
                      }}
                      sx={{
                        justifyContent: 'center'
                      }}
                    >
                      Settings
                    </MenuItem>
                    <MenuItem
                      onClick={() => {
                        setAnchorElUser(null)

                        navigate(appPublicRoutes.verify)
                      }}
                      sx={{
                        justifyContent: 'center'
                      }}
                    >
                      Verify
                    </MenuItem>
                    <Link
                      to={appPublicRoutes.source}
                      target="_blank"
                      style={{ color: 'inherit', textDecoration: 'inherit' }}
                    >
                      <MenuItem
                        sx={{
                          justifyContent: 'center'
                        }}
                      >
                        Source
                      </MenuItem>
                    </Link>
                    <MenuItem
                      onClick={handleLogout}
                      sx={{
                        justifyContent: 'center'
                      }}
                    >
                      Logout
                    </MenuItem>
                  </Menu>
                </>
              )}
            </Box>
          </Toolbar>
        </Container>
      </AppBarMui>
    </>
  )
}
