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

import { useEffect, useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import {
  setAuthState,
  setMetadataEvent,
  userLogOutAction
} from '../../store/actions'
import { State } from '../../store/rootReducer'
import { Dispatch } from '../../store/store'
import Username from '../username'

import { Link, useNavigate } from 'react-router-dom'
import { MetadataController, NostrController } from '../../controllers'
import {
  appPublicRoutes,
  appPrivateRoutes,
  getProfileRoute
} from '../../routes'
import {
  clearAuthToken,
  hexToNpub,
  saveNsecBunkerDelegatedKey,
  shorten
} from '../../utils'
import styles from './style.module.scss'
import { setUserRobotImage } from '../../store/userRobotImage/action'
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'

const metadataController = MetadataController.getInstance()

export const AppBar = () => {
  const navigate = useNavigate()

  const dispatch: Dispatch = useDispatch()

  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 { picture, display_name, name } = JSON.parse(
          metadataState.content
        )

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

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

        setUsername(shorten(display_name || name || npub, 7))
      } 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()
    dispatch(
      setAuthState({
        keyPair: undefined,
        loggedIn: false,
        usersPubkey: undefined,
        loginMethod: undefined,
        nsecBunkerPubkey: undefined
      })
    )
    dispatch(setMetadataEvent(metadataController.getEmptyMetadataEvent()))
    dispatch(setUserRobotImage(null))

    // clear authToken saved in local storage
    clearAuthToken()

    dispatch(userLogOutAction())

    // update nsecBunker delegated key after logout
    const nostrController = NostrController.getInstance()
    const newDelegatedKey = nostrController.generateDelegatedKey()
    saveNsecBunkerDelegatedKey(newDelegatedKey)

    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}>
              SIGit is currently Alpha software (available for internal
              testing), use at your own risk!
              <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={() => {
                    navigate(appPublicRoutes.nostr)
                  }}
                  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>
    </>
  )
}
