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

import { useEffect, useState } from 'react'
import { useSelector } from 'react-redux'
import { State } from '../../store/rootReducer'
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 = useSelector((state: State) => state.auth)
  const metadataState = useSelector((state: State) => state.metadata)
  const userRobotImage = useSelector((state: 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 Alpha software (available for internal
                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={() => navigate('/')} />
            </Box>

            <Box className={styles.rightSideBox}>
              {!isAuthenticated && (
                <Button
                  startIcon={<ButtonIcon />}
                  onClick={() => {
                    launchNostrLoginDialog('welcome')
                  }}
                  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>
    </>
  )
}
