import type { IconName } from '@blueprintjs/core'
import { Colors, Tag } from '@blueprintjs/core'
import { css, cx } from '@emotion/css'
import type { CSSProperties, FC, ReactNode } from 'react'
import { useMemo } from 'react'

export const tag = css`
  /* prevent stretching */
  align-self: center;
`

const read = css`
  background-color: ${Colors.GREEN3}4d !important;
`
const notRead = css`
  background-color: ${Colors.ORANGE3}4d !important;
`
const achieved = css`
  background-color: ${Colors.GREEN3} !important;
  color: ${Colors.WHITE} !important;
`
const notAchieved = css`
  background-color: ${Colors.RED3} !important;
  color: ${Colors.WHITE} !important;
`

export type StyledTagProps = {
  style?: CSSProperties
  className?: string
} & (
  | {
      isRead?: boolean
      isAchieved?: undefined
    }
  | {
      isRead?: undefined
      isAchieved?: boolean
    }
)

const StyledTag: FC<
  StyledTagProps & {
    content: ReactNode
  }
> = ({ content, style, className, isRead, isAchieved }) => {
  const icon = useMemo<IconName | undefined>(() => {
    if (isAchieved !== undefined) {
      return isAchieved ? 'tick' : 'cross'
    }
    return undefined
  }, [isAchieved])

  const achievedTitle =
    typeof isAchieved === 'boolean'
      ? isAchieved
        ? 'Achieved'
        : 'Not achieved'
      : undefined
  const readTitle =
    typeof isRead === 'boolean' ? (isRead ? 'Read' : 'Not read') : undefined

  return (
    <Tag
      minimal
      round
      icon={icon}
      style={style}
      title={achievedTitle || readTitle}
      className={cx({
        [tag]: true,
        [className || '']: className !== undefined,
        [isRead ? read : notRead]: isRead !== undefined,
        [isAchieved ? achieved : notAchieved]: isAchieved !== undefined,
      })}
    >
      {content}
    </Tag>
  )
}

export default StyledTag
