/*
 * 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 from 'react'

import { useCopyToClipboard } from 'usehooks-ts'

import CopySVG from '../../assets/copy.svg'
import LogoutSVG from '../../assets/logout.svg'
import NewTabSVG from '../../assets/new-tab.svg'
import { useWallet } from '../../store/wallet'
import { getAccountAddressExplorerUrl, getWalletIcon, truncateString } from '../../utils'
import { Modal } from '../Modal/Modal'

type Props = {
  open: boolean
  onClose: () => void
}

export const AccountModal: React.FC<Props> = ({ open, onClose }: Props) => {
  const { account, disconnect, prefixCls, chainId, chains, walletState } = useWallet()
  const [, copy] = useCopyToClipboard()

  if (!account) {
    return null
  }

  const chain = chains.find((item) => item.chainId === chainId)

  const accountUrl = chain ? getAccountAddressExplorerUrl(chain, account) : undefined

  return (
    <Modal
      closeOnOverlayClick
      classNames={{ modal: `${prefixCls}accountModal` }}
      title="Account"
      open={open}
      onClose={onClose}
    >
      <div className={`${prefixCls}connectionWrap`}>
        <img
          src={walletState ? getWalletIcon(walletState.icon) : undefined}
          alt={`${walletState ? walletState.label : 'wallet'} logo`}
        />

        <div className={`${prefixCls}connectionDetail`}>
          <div className={`${prefixCls}connectionStatus`}>
            Connected with {walletState ? walletState.label : 'wallet'}
          </div>
          <div className={`${prefixCls}accountAddress`}>{truncateString(account)}</div>
        </div>

        <div className={`${prefixCls}buttonGroup`}>
          <button className={`${prefixCls}accountButton`} onClick={() => copy(account)}>
            <CopySVG className={`${prefixCls}buttonIcon`} />
          </button>
          {accountUrl ? (
            <a
              href={accountUrl}
              className={`${prefixCls}accountButton`}
              target="_blank"
              rel="noreferrer"
            >
              <NewTabSVG className={`${prefixCls}buttonIcon`} />
            </a>
          ) : null}
          <button
            className={`${prefixCls}accountButton ${prefixCls}accountLogoutButton`}
            onClick={disconnect}
          >
            <LogoutSVG className={[`${prefixCls}buttonIcon`, `${prefixCls}logoutIcon`].join(' ')} />
          </button>
        </div>
      </div>
    </Modal>
  )
}
