import type { TeamState } from '@/clientsettings/vars/teams'
import type { LinkType } from '@/components/LinkButton'
import LinkButton from '@/components/LinkButton'
import TeamLabel from '@/components/TeamLabel'
import type { Path } from '@/router'
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.team.exercise.id,
            teamId: teamState.team.id,
          },
        },
      ]
    }
    return [
      `/instructor/:exerciseId/:teamId/${pathMatches.slice(4).join('/')}` as Path,
      {
        params: {
          exerciseId: teamState.team.exercise.id,
          teamId: teamState.team.id,
        },
      },
    ]
  }, [matches, teamState.team.exercise.id, teamState.team.id])

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

export default TeamButton
