import React, { useMemo } from 'react'

import { getIntegrationIcon } from '~/resources/integration-icons'

import { DestinationImage, DestinationItem, DestinationList } from './style'


export type EventDestinationsProps = {
  destinations: string[]
}

export const EventDestinations = ({ destinations }: EventDestinationsProps) => {
  const { showable, remainder } = useMemo(() => {
    const sorted = destinations?.slice().sort((a) => (getIntegrationIcon(a) ? -1 : 1))
    const showable = sorted?.length > 4 ? sorted?.slice(0, 3) : sorted
    const remainder = sorted?.length - showable?.length

    return { showable, remainder }
  }, [destinations])

  const renderDestinationIcon = (destName: string) => {
    const iconDataURI = getIntegrationIcon(destName)
    return iconDataURI ? <DestinationImage uri={iconDataURI} /> : destName[0].toUpperCase()
  }

  if (!destinations?.length) {
    return null
  }

  return (
    <DestinationList>
      {showable.map((destName, i) => (
        <DestinationItem key={i}>{renderDestinationIcon(destName)}</DestinationItem>
      ))}
      {remainder > 0 && <DestinationItem pill>{remainder} more</DestinationItem>}
    </DestinationList>
  )
}
