import TabButton from '@/analyst/OverflowTabs/TabButton'
import type { TeamState } from '@/clientsettings/vars/teams'
import { useTeamStateMap } from '@/clientsettings/vars/teams'
import { Colors } from '@blueprintjs/colors'
import { Button } from '@blueprintjs/core'
import { css, cx } from '@emotion/css'
import { useClickAway } from 'ahooks'
import type { FC } from 'react'
import { memo, useMemo, useRef, useState } from 'react'
import { useNavigate, useParams } from 'react-router-dom'

const barClass = css`
  top: 0;
  left: 0;
  right: 0;
  min-height: 48px;
  padding-top: 0.25rem;
  margin-bottom: 0.25rem;
  padding-bottom: 0.25rem;
  z-index: 10;

  border-bottom: 1px solid ${Colors.BLACK}26;
  background-color: white;

  & > div {
    display: flex;
    justify-content: space-between;
    overflow-x: auto;
    overflow-y: hidden;
  }
  .teamTabs {
    background-color: white;
  }
  #topnavPortal:not(:empty) {
    padding-left: 0.75rem;
    border-left: 1px solid ${Colors.BLACK}26;
  }
  #backnavPortal:not(:empty) {
    padding-right: 0.75rem;
    border-right: 1px solid ${Colors.BLACK}26;
    margin-right: 0.75rem;
  }
  .bp5-dark &,
  .bp5-dark & #backnavPortal:not(:empty),
  .bp5-dark & #topnavPortal:not(:empty),
  .bp5-dark & .teamTabs {
    border-color: ${Colors.WHITE}33 !important;
    background-color: ${Colors.DARK_GRAY3} !important;
  }
  #dropdownEnabler {
    display: none;
  }

  @media only screen and (max-width: 960px) {
    #dropdownEnabler {
      display: block;
    }
    > div {
      flex-wrap: wrap;
      gap: 0rem;
      /* justify-content: unset; */
    }
    .enabled + .teamTabs {
      display: flex;
    }
    .teamTabs {
      display: none;
      width: 100%;
      flex-direction: column;
      position: absolute;
      top: 3rem;
      left: 0;
      z-index: 500;
      border-bottom-width: 1px;
      border-bottom-style: solid;
      box-shadow: 0px 15px 30px rgba(0, 0, 0, 0.2);
    }
    #backnavPortal:not(:empty) {
      border-right: none;
      padding-right: 0;
    }
    #topnavPortal:not(:empty) {
      border-left: none;
      padding-left: 0;
    }
  }
`

const Title: FC<{
  team: TeamState
  onClick: (teamId: string) => void
  active?: boolean
}> = ({ team, onClick, active }) => (
  <TabButton
    key={team.team.id || 'all'}
    active={active}
    onClick={() => onClick(team.team.id || '')}
  >
    <div
      style={{
        display: 'flex',
        flexDirection: 'column',
      }}
    >
      <p style={{ marginBottom: 3, whiteSpace: 'nowrap' }}>{team.team.name}</p>
    </div>
  </TabButton>
)

const Dropdown: FC<{
  teamStates: TeamState[]
  teamId?: string
}> = ({ teamStates, teamId }) => {
  const [open, setOpen] = useState(false)
  const selectedTeam = useMemo<TeamState>(
    () =>
      teamStates.find(teamState => teamState.team.id === teamId) ?? {
        inactive: false,
        show: true,
        team: {
          exercise: {
            id: '-1',
            name: '',
          },
          id: '-1',
          name: 'Select team',
          role: '',
        },
      },
    [teamId, teamStates]
  )

  const butt = useRef<HTMLButtonElement>(null)
  useClickAway(() => {
    setOpen(false)
  }, butt)

  return (
    <Button
      ref={butt}
      text={selectedTeam.team.name}
      minimal
      id='dropdownEnabler'
      onClick={() => {
        setOpen(prev => !prev)
      }}
      className={cx({
        ['enabled']: open,
        [css``]: open,
      })}
      icon={open ? 'chevron-up' : 'chevron-down'}
    />
  )
}

const TeamTabs = () => {
  const teamStateMap = useTeamStateMap()
  const { teamId } = useParams()
  const nav = useNavigate()

  const teamStates = useMemo(() => Object.values(teamStateMap), [teamStateMap])
  const selectedTeamStates = useMemo(
    () => teamStates.filter(teamState => teamState.show),
    [teamStates]
  )

  // TODO: demogrify the teamtabs
  return (
    <div id='teamBar' className={barClass}>
      <div>
        <div id='backnavPortal' />
        <div id='tabs'>
          <Dropdown teamId={teamId} teamStates={selectedTeamStates} />
          <div className='teamTabs'>
            {selectedTeamStates.map(teamState => (
              <Title
                key={teamState.team.id}
                team={teamState}
                active={teamId === teamState.team.id}
                onClick={newId => {
                  const path = window.location.pathname.split('/')
                  path[3] = newId.toString()
                  nav(path.join('/'))
                }}
              />
            ))}
          </div>
        </div>
        <div id='topnavPortal' />
      </div>
    </div>
  )
}

export default memo(TeamTabs)
