import React from 'react'
import { User } from '../../../types'
import _ from 'lodash'
import { npubToHex, getProfileUsername } from '../../../utils'
import { AvatarIconButton } from '../../UserAvatarIconButton'
import styles from './Counterpart.module.scss'
import { NDKUserProfile } from '@nostr-dev-kit/ndk'

interface CounterpartProps {
  npub: string
  userProfiles: {
    [key: string]: NDKUserProfile
  }
  signers: User[]
}

export const Counterpart = React.memo(
  ({ npub, userProfiles, signers }: CounterpartProps) => {
    let displayValue = _.truncate(npub, { length: 16 })

    const signer = signers.find((u) => u.pubkey === npubToHex(npub))
    if (signer) {
      const profile = userProfiles[signer.pubkey]
      displayValue = getProfileUsername(npub, profile)

      return (
        <div className={styles.counterpartSelectValue}>
          <AvatarIconButton
            src={profile?.image}
            hexKey={signer.pubkey || undefined}
            sx={{
              padding: 0,
              marginRight: '6px',
              '> img': {
                width: '21px',
                height: '21px'
              }
            }}
          />
          {displayValue}
        </div>
      )
    }

    return displayValue
  }
)
