/*
 * 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, { useCallback, useMemo, useState } from 'react'

import { SwitchNetworkMenu } from '../'
import CaretDownSVG from '../../assets/caret-down.svg'
import WarningSVG from '../../assets/warning.svg'
import { useChainIsSupported, useWallet } from '../../store/wallet'

export const Network: React.FC = () => {
  const { chainId, chains, prefixCls } = useWallet()
  const chainIsSupported = useChainIsSupported(chainId)

  const [menuIsOpen, setMenuIsOpen] = useState<boolean>(false)

  const openMenu = useCallback(() => {
    if (!menuIsOpen) {
      setMenuIsOpen(true)
    }
  }, [menuIsOpen])

  const closeMenu = useCallback(() => setMenuIsOpen(false), [])

  const chain = useMemo(() => chains.find((item) => item.chainId === chainId), [chainId, chains])

  if (!chain) {
    return null
  }

  return (
    <div
      role="button"
      tabIndex={0}
      className={`${prefixCls}network`}
      onMouseEnter={openMenu}
      onFocus={openMenu}
      onMouseLeave={closeMenu}
      onBlur={closeMenu}
    >
      <div
        className={[
          `${prefixCls}networkSelect`,
          !chainIsSupported ? `${prefixCls}networkSelectWarning` : ''
        ].join(' ')}
      >
        {!chainIsSupported ? (
          <>
            <WarningSVG className={`${prefixCls}warningIcon`} />
            Switch network
          </>
        ) : (
          <>
            <img
              src={chain.iconUrl}
              alt={`${chain.chainName} logo`}
              className={`${prefixCls}networkLogo`}
            />
            {chain.chainName}
          </>
        )}
        <CaretDownSVG className={`${prefixCls}caretDownIcon`} />
      </div>
      <SwitchNetworkMenu open={menuIsOpen} />
    </div>
  )
}
