import TabButton from '@/analyst/OverflowTabs/TabButton'
import {
  Boundary,
  ButtonGroup,
  Classes,
  Divider,
  OverflowList,
  Popover,
} from '@blueprintjs/core'
import { css } from '@emotion/css'
import type { Team } from '@inject/graphql/fragment-types'
import Container from '@inject/shared/components/Container'
import type { FC, ReactNode } from 'react'
import { useState } from 'react'

const wrapper = css`
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: auto;
`

const container = css`
  flex: 1;
  padding: 1rem;
  overflow: auto;
  display: flex;
  flex-direction: column;
  gap: 1rem;
`

interface TeamSelectPageProps {
  teams: Team[]
  getChildren: (selectedTeam: Team) => ReactNode
}

const TeamSelectPage: FC<TeamSelectPageProps> = ({ teams, getChildren }) => {
  const [selectedTeam, setSelectedTeam] = useState<Team>(teams[0])
  const handleClick = (item: Team) => () => setSelectedTeam(item)

  const overflowRenderer = (overflowItems: Team[]) => (
    <div style={{ marginLeft: 'auto' }}>
      <Popover
        content={
          <ButtonGroup vertical style={{ padding: 8 }}>
            {overflowItems.map(item => (
              <TabButton
                key={item.id}
                active={selectedTeam.id === item.id}
                onClick={handleClick(item)}
              >
                {item.name}
              </TabButton>
            ))}
          </ButtonGroup>
        }
        position='bottom-left'
      >
        <span className={Classes.BREADCRUMBS_COLLAPSED} style={{ margin: 4 }} />
      </Popover>
    </div>
  )

  const visibleItemRenderer = (item: Team) => (
    <TabButton
      key={item.id}
      active={selectedTeam.id === item.id}
      onClick={handleClick(item)}
    >
      {item.name}
    </TabButton>
  )

  return (
    <div className={wrapper}>
      <OverflowList
        style={{ alignItems: 'center', marginBottom: 8 }}
        collapseFrom={Boundary.END}
        items={teams}
        overflowRenderer={overflowRenderer}
        visibleItemRenderer={visibleItemRenderer}
      />

      <Divider />

      <Container className={container}>{getChildren(selectedTeam)}</Container>
    </div>
  )
}

export default TeamSelectPage
