import LinkButton from '@/components/LinkButton'
import type { Channel } from '@inject/graphql/fragment-types'
import type { VariablesOf } from '@inject/graphql/graphql'
import { setIsUnreadChannel } from '@inject/graphql/mutations.client'
import { useMemo, type FC } from 'react'
import { useLocation } from 'react-router-dom'
import { useClient } from 'urql'
import { getActive, getIcon, getLink } from '../ChannelButton'

export interface ChannelButtonProps {
  exerciseId: string
  teamId: string
  linkTo: 'trainee' | 'instructor'
  channel: Channel
  hideLabel?: boolean
}

const OverviewChannelButton: FC<ChannelButtonProps> = ({
  channel,
  exerciseId,
  teamId,
  linkTo,
  hideLabel,
}) => {
  const { pathname } = useLocation()
  const client = useClient()

  const isUnread = useMemo(() => {
    const needle = channel.readReceipt.find(
      readReceipt => readReceipt.teamId === teamId
    )
    return needle?.isUnread
  }, [channel.readReceipt, teamId])

  const children = useMemo(() => {
    if (hideLabel) {
      return undefined
    }
    if (isUnread) {
      return <b>{channel.displayName}</b>
    }
    return channel.displayName
  }, [channel.displayName, hideLabel, isUnread])

  return (
    <LinkButton
      key={channel.id}
      link={getLink(channel, exerciseId, teamId, linkTo)}
      button={{
        icon: getIcon(channel.type),
        title: channel.displayName,
        alignText: 'left',
        active: getActive(channel, linkTo, pathname),
        intent: isUnread ? 'warning' : undefined,
        onClick: () =>
          client
            .mutation<unknown, VariablesOf<typeof setIsUnreadChannel>>(
              setIsUnreadChannel,
              {
                channelId: channel.id,
                teamId,
                isUnread: false,
              }
            )
            .toPromise(),
        children,
        ellipsizeText: true,
      }}
    />
  )
}

export default OverviewChannelButton
