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 { useMatch } from 'react-router-dom'
import { useClient } from 'urql'
import { 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 client = useClient()

  const active = useMatch({
    path: `/${linkTo}/:exerciseId/:teamId/${channel.id}/`,
    end: false,
  })

  const isUnread = useMemo(() => {
    const needle = channel.readReceipt.find(
      readReceipt => readReceipt.teamId === teamId
    )
    return needle?.isUnread
  }, [channel, 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: !!active,
        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
