import type { LinkType } from '@/components/LinkButton'
import LinkButton from '@/components/LinkButton'
import TeamLabel from '@/components/TeamLabel'
import type { Path } from '@/router'
import type { TeamState } from '@inject/graphql/fragment-types'
import { useMemo, type FC } from 'react'
import { useMatch, useMatches } from 'react-router-dom'

interface TeamButtonProps {
  teamState: TeamState
  hideLabel: boolean | undefined
}

const TeamButton: FC<TeamButtonProps> = ({ teamState, hideLabel }) => {
  const match = useMatch({
    path: '/instructor/:exercise/:teamId/',
    end: false,
  })
  const matches = useMatches()
  const link: LinkType = useMemo(() => {
    // deepest nested route that matches the current URL
    const match = matches.at(-1)

    /*
     * expected pathname is /instructor/:exerciseId/:teamId/...,
     * therefore the pathMatches should be ['', 'instructor', ':exerciseId', ':teamId', ...]
     */
    const pathMatches = match?.pathname.split('/') || []
    if (pathMatches.length <= 3) {
      return [
        '/instructor/:exerciseId/:teamId',
        {
          params: {
            exerciseId: teamState.exercise.id,
            teamId: teamState.id,
          },
        },
      ]
    }
    return [
      `/instructor/:exerciseId/:teamId/${pathMatches.slice(4).join('/')}` as Path,
      {
        params: {
          exerciseId: teamState.exercise.id,
          teamId: teamState.id,
        },
      },
    ]
  }, [matches, teamState.exercise.id, teamState.id])

  return (
    <LinkButton
      key={teamState.id}
      link={link}
      button={{
        active: teamState.id === match?.params.teamId,
        alignText: 'left',
        fill: true,
        minimal: true,
        title: teamState.name,
        children: (
          <TeamLabel
            hideLabel={hideLabel}
            teamId={teamState.id}
            teamName={teamState.name}
          />
        ),
      }}
    />
  )
}

export default TeamButton
