import useTools from '@/analyst/dataHooks/useTools'
import useToolsWithEmailsSent from '@/analyst/dataHooks/useToolsWithEmailsSent'
import {
  Boundary,
  ButtonGroup,
  Classes,
  OverflowList,
  Popover,
} from '@blueprintjs/core'
import type { Tool } from '@inject/graphql/fragments/Tool.generated'
import useEmailsEnabled from '@inject/graphql/utils/useEmailsEnabled'
import { useContext } from 'react'
import ExerciseContext from '../../ExerciseContext'
import TabButton from '../../OverflowTabs/TabButton'
import SelectedContext from '../SelectedContext'

const ToolSelector = () => {
  const { selectedReducer } = useContext(SelectedContext)

  const [selectedState, selectedDispatch] = selectedReducer

  const { exercise } = useContext(ExerciseContext)
  const toolsWithEmailsSent = useToolsWithEmailsSent()
  const tools = useTools()

  const emailsEnabled = useEmailsEnabled({
    variables: { exerciseId: exercise.id },
  })

  const handleClick = (item: Tool | undefined) => () =>
    selectedDispatch({ type: 'selectTool', tool: item })

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

  const visibleItemRenderer = (item: Tool | undefined) => (
    <TabButton
      key={item?.id || 'AllToolsTab'}
      active={selectedState.tool?.id === item?.id}
      onClick={handleClick(item)}
    >
      {item?.name || 'All tools'}
    </TabButton>
  )

  return (
    <OverflowList
      style={{ alignItems: 'center', marginBottom: 8 }}
      collapseFrom={Boundary.END}
      items={[undefined, ...(emailsEnabled ? toolsWithEmailsSent : tools)]}
      overflowRenderer={overflowRenderer}
      visibleItemRenderer={visibleItemRenderer}
    />
  )
}

export default ToolSelector
