import { Box, IconButton, Typography, useTheme } from '@mui/material'
import { useSelector } from 'react-redux'
import { useNavigate } from 'react-router-dom'
import { getProfileRoute } from '../routes'
import { State } from '../store/rootReducer'
import { hexToNpub } from '../utils'

type Props = {
  username: string
  avatarContent: string
  handleClick: (event: React.MouseEvent<HTMLElement>) => void
}

const Username = ({ username, avatarContent, handleClick }: Props) => {
  const hexKey = useSelector((state: State) => state.auth.usersPubkey)

  return (
    <div
      style={{
        display: 'flex',
        flexDirection: 'row',
        justifyContent: 'end',
        alignItems: 'center',
        gap: '12px'
      }}
    >
      <Typography
        variant="h6"
        sx={{
          fontWeight: 500,
          fontSize: '14px',
          color: 'var(--text-color)',
          display: { xs: 'none', md: 'flex' }
        }}
      >
        {username}
      </Typography>
      <IconButton
        aria-label="account of current user"
        aria-controls="menu-appbar"
        aria-haspopup="true"
        onClick={handleClick}
        color="inherit"
      >
        <img
          src={avatarContent}
          alt="user-avatar"
          className="profile-image"
          style={{
            borderWidth: '3px',
            borderStyle: hexKey ? 'solid' : 'none',
            borderColor: `#${hexKey?.substring(0, 6)}`
          }}
        />
      </IconButton>
    </div>
  )
}

export default Username

type UserProps = {
  pubkey: string
  name: string
  image?: string
}

/**
 *  This component will be used for the displaying username and profile picture.
 *  If image is not available, robohash image will be displayed
 */
export const UserComponent = ({ pubkey, name, image }: UserProps) => {
  const theme = useTheme()
  const navigate = useNavigate()

  const npub = hexToNpub(pubkey)
  const roboImage = `https://robohash.org/${npub}.png?set=set3`

  const handleClick = (e: React.MouseEvent<HTMLElement, MouseEvent>) => {
    e.stopPropagation()
    // navigate to user's profile
    navigate(getProfileRoute(pubkey))
  }

  return (
    <Box
      sx={{ display: 'flex', alignItems: 'center', gap: '10px', flexGrow: 1 }}
    >
      <img
        src={image || roboImage}
        alt="User Image"
        className="profile-image"
        style={{
          borderWidth: '3px',
          borderStyle: 'solid',
          borderColor: `#${pubkey.substring(0, 6)}`
        }}
        onClick={handleClick}
      />
      <Typography
        component="label"
        sx={{
          textAlign: 'center',
          cursor: 'pointer',
          color: theme.palette.text.primary
        }}
        onClick={handleClick}
      >
        {name}
      </Typography>
    </Box>
  )
}
