/*
 * Copyright (c) 2022 @automata-network/wallet-sdk authors and contributors.
 * This software may be modified and distributed under the terms of UNLICENSED
 * license. Refer to the LICENSE file for details.
 */
import React, { KeyboardEvent, useCallback, useState } from 'react'

import { AccountAvatar, AccountModal } from '../'
import { useWallet } from '../../store/wallet'
import { truncateString } from '../../utils'

type Props = {
  account: string
  avatarPosition?: 'left' | 'right'
  className?: string
  withAvatar?: boolean
}

export const Account: React.FC<Props> = ({
  account,
  avatarPosition,
  className,
  withAvatar = true
}) => {
  const [isAccountModalOpen, setAccountModalOpen] = useState<boolean>(false)
  const { prefixCls } = useWallet()

  const openAccountModal = useCallback(() => setAccountModalOpen(true), [])
  const closeAccountModal = useCallback(() => setAccountModalOpen(false), [])

  const onAccountEnterDown = useCallback(
    (e: KeyboardEvent<HTMLDivElement>) => {
      const key = e.key.toLowerCase()
      if (key === 'enter') {
        openAccountModal()
      }
    },
    [openAccountModal]
  )

  return (
    <>
      <div
        className={[`${prefixCls}account`, className].join(' ')}
        role="button"
        tabIndex={0}
        onClick={openAccountModal}
        onKeyDown={onAccountEnterDown}
        style={{
          flexDirection: avatarPosition === 'right' ? 'row-reverse' : 'row'
        }}
      >
        {withAvatar && <AccountAvatar className={`${prefixCls}accountAvatar`} account={account} />}
        {truncateString(account)}
      </div>

      <AccountModal open={isAccountModalOpen} onClose={closeAccountModal} />
    </>
  )
}
