/*
 * 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 } from 'react'
import 'react-responsive-modal/styles.css'

import { useWallet } from '../../store/wallet'

type Props = {
  open: boolean
}

export const SwitchNetworkMenu: React.FC<Props> = ({ open }) => {
  const { chains, switchChain, prefixCls } = useWallet()

  const onNetworkOptionClick = useCallback(
    async (chainId: string) => {
      await switchChain(chainId)
    },
    [switchChain]
  )

  const onNetworkOptionEnterDown = useCallback(
    (chainId: string, e: KeyboardEvent<HTMLDivElement>) => {
      const key = e.key.toLowerCase()
      if (key === 'enter') {
        return onNetworkOptionClick(chainId)
      }
    },
    [onNetworkOptionClick]
  )

  if (!open) {
    return null
  }

  return (
    <div className={`${prefixCls}switchNetworkMenu`}>
      <div className={`${prefixCls}card`}>
        <div className={`${prefixCls}title`}>Select a supported network</div>
        <div className={`${prefixCls}listWrapper`}>
          {chains.map((chain) => (
            <div
              tabIndex={0}
              role="button"
              key={`network_${chain.chainId}`}
              className={`${prefixCls}listItem`}
              onClick={() => {
                onNetworkOptionClick(chain.chainId)
              }}
              onKeyDown={(e: KeyboardEvent<HTMLDivElement>) =>
                onNetworkOptionEnterDown(chain.chainId, e)
              }
            >
              <span className={`${prefixCls}networkLogo`}>
                {chain.iconUrl ? (
                  <img src={chain.iconUrl} alt={`${chain.chainName} logo`} />
                ) : (
                  chain.chainName.charAt(0)
                )}
              </span>
              {chain.chainName}
            </div>
          ))}
        </div>
      </div>
    </div>
  )
}
