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

import { ProfileTypes, SportTypes } from 'config'

import {
  getProfileFallbackLogo,
  getProfileLogo,
  readToken,
} 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,
  size?: number,
  sportType: SportTypes,
  title?: string,
}

type AwsMediaFlags = {
  cover_url: 'string' | null,
  landing_mobile_url: 'string' | null,
  landing_url: 'string' | null,
  logo_url: 'string' | null,
}

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

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

  useEffect(() => {
    (async () => {
      // если нет logoUrl, то нужно делать запрос в aws
      // если logoUrl === null, то это уже ответ с aws
      if (logoUrl === null) {
        setImageSource(scoutSrc)
        return
      }

      if (logoUrl) {
        setImageSource(logoUrl)
        return
      }

      try {
        const { logo_url }: AwsMediaFlags = await (await fetch(awsSrc, {
          headers: { Authorization: `Bearer ${readToken()}` },
        })).json()

        if (logo_url) {
          setImageSource(logo_url)
          return
        }
        setImageSource(scoutSrc)
      } catch (error) {
        setImageSource(scoutSrc)
      }
    })()
  }, [awsSrc, logoUrl, scoutSrc])

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