import {
  Fragment,
  useEffect,
  useState,
} from 'react'

import { ProfileTypes, SportTypes } from 'config'

import {
  getProfileFallbackLogo,
  getProfileLogo,
} from 'helpers'

import { Image } from 'features/Common'
import type { ObjectWithName } from 'features/Name'
import { useName } from 'features/Name'

type ProfileImageProps = {
  alt?: string,
  altNameObj?: ObjectWithName,
  className?: string,
  id: number,
  logoUrl?: string | null,
  nameAsTitle?: boolean,
  onLoad?: () => void,
  prefix?: string,
  profileType: ProfileTypes,
  sportType: SportTypes,
  title?: string,
}

export const ProfileLogo = ({
  alt,
  altNameObj,
  className,
  id,
  logoUrl,
  nameAsTitle,
  onLoad,
  prefix,
  profileType,
  sportType,
  title,
}: ProfileImageProps) => {
  const [imageSource, setImageSource] = useState('')

  const altName = useName(altNameObj || {}, prefix)
  const titleText = nameAsTitle ? altName : title
  const awsSrc = getProfileLogo({
    id,
    profileType,
    sportType,
  })
  const fallbackSrc = getProfileFallbackLogo(profileType)

  useEffect(() => {
    setImageSource(logoUrl || awsSrc)
  }, [awsSrc, logoUrl])

  return (
    <Fragment>
      {Boolean(imageSource) && (
        <Image
          alt={alt || altName}
          src={imageSource}
          fallbackSrc={fallbackSrc}
          className={className}
          onLoad={onLoad}
          title={titleText}
        />
      )}
    </Fragment>
  )
}
