import React, {
  type FC,
  type MouseEventHandler,
  useCallback,
  useMemo,
} from 'react';

import { useWallet } from '@solana/wallet-adapter-react';

import {
  useConnectWallet,
  useWalletModal,
} from '../hooks';
import {
  Button,
  type ButtonProps,
} from './Button';
import { WalletIcon } from './WalletIcon';

export const WalletConnectButton: FC<ButtonProps> = ({ children, disabled, onClick, ...props }) => {
  const { wallet, connecting, connected } = useWallet()
  const { connectWallet } = useConnectWallet()
  const { trans } = useWalletModal()

  const handleClick: MouseEventHandler<HTMLButtonElement> = useCallback(
    (event) => {
      if (onClick) onClick(event)
      if (!event.defaultPrevented) connectWallet()
    },
    [onClick, connectWallet],
  )

  const content = useMemo(() => {
    if (children) return children
    if (connecting) return `${trans.connecting} ...`
    if (connected) return trans.connected
    if (wallet) return trans.connect
    return trans.connect_wallet
  }, [children, connecting, connected, wallet, trans])

  return (
    <Button
      className="wallet-adapter-button-trigger"
      data-connecting={connecting}
      data-connected={connected}
      disabled={disabled || !wallet || connecting || connected}
      beginIcon={wallet ? <WalletIcon wallet={wallet} /> : undefined}
      onClick={handleClick}
      {...props}
    >
      <span className="wallet-adapter-button-content">{content}</span>
    </Button>
  )
}
