import { Classes, Tag } from '@blueprintjs/core'
import { css, cx } from '@emotion/css'
import ColorBox from '@inject/shared/components/ColorBox'
import { ellipsized } from '@inject/shared/css/textOverflow'
import { useMemo, type FC } from 'react'

const wrapper = css`
  display: flex;
  align-items: center;
  justify-content: center;
  max-width: 100%;
  padding: 0.25rem 0.5rem;
`

const labelClass = css`
  flex: 1;
`

interface TeamLabelProps {
  hideLabel?: boolean
  teamId: string
  teamName: string
  teamRole?: string
  exerciseName?: string
  inactive?: boolean
}

const TeamLabel: FC<TeamLabelProps> = ({
  hideLabel,
  teamId,
  teamName,
  teamRole,
  exerciseName,
  inactive,
}) => {
  const label = useMemo(
    () => (
      <div className={cx(labelClass, ellipsized)}>
        <div>{teamName}</div>
        {teamRole && (
          <div className={Classes.TEXT_MUTED}>{`role: ${teamRole}`}</div>
        )}
        {exerciseName && (
          <div
            title={exerciseName}
            className={cx(Classes.TEXT_MUTED, ellipsized)}
          >
            {exerciseName}
          </div>
        )}
      </div>
    ),
    [exerciseName, teamName, teamRole]
  )

  const colorbox = useMemo(
    () => (
      <ColorBox
        title={teamName}
        style={{
          // the size of Blueprint icons
          width: '16px',
          height: '16px',
          // TODO: this should be the same as the margin of an icon in a button
          marginRight: hideLabel ? undefined : '7px',
        }}
        id={Number(teamId)}
      />
    ),
    [hideLabel, teamId, teamName]
  )

  const content = useMemo(() => {
    if (hideLabel) {
      return colorbox
    }

    return (
      <>
        {colorbox}
        {label}
        {inactive && (
          <Tag style={{ marginLeft: '1ch' }} minimal intent='warning'>
            inactive
          </Tag>
        )}
      </>
    )
  }, [colorbox, hideLabel, inactive, label])

  return <div className={wrapper}>{content}</div>
}

export default TeamLabel
