import useEmailThreads from '@/analyst/dataHooks/useEmailThreads'
import { useNavigate } from '@/router'
import {
  Boundary,
  ButtonGroup,
  Classes,
  OverflowList,
  Popover,
} from '@blueprintjs/core'
import type { Team } from '@inject/graphql/fragments/Team.generated'
import type { FC } from 'react'
import { useContext, useState } from 'react'
import TeamEmails from '../../email/TeamEmails'
import ExerciseContext from '../ExerciseContext'
import TabButton from '../OverflowTabs/TabButton'
import { EmailSelection } from '../utilities'

interface EmailsProps {
  exerciseId: string
  tab: EmailSelection
  threadId: string | undefined
}

const Emails: FC<EmailsProps> = ({ exerciseId, tab, threadId }) => {
  const { exercise } = useContext(ExerciseContext)
  const emailThreads = useEmailThreads()

  const nav = useNavigate()

  const [selectedTeam, setSelectedTeam] = useState<Team>(exercise.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 active={selectedTeam.id === item.id} onClick={handleClick(item)}>
      {item.name}
    </TabButton>
  )

  const filteredEmailThreads = emailThreads.filter(emailThread =>
    emailThread.participants
      .flatMap(participant => participant.team?.id)
      .includes(selectedTeam.id)
  )

  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
      <OverflowList
        style={{ alignItems: 'center', marginBottom: 8 }}
        collapseFrom={Boundary.END}
        items={exercise.teams}
        overflowRenderer={overflowRenderer}
        visibleItemRenderer={visibleItemRenderer}
      />

      <div style={{ overflow: 'auto', flex: 1 }}>
        <TeamEmails
          exerciseId={exercise.id}
          teamId={selectedTeam.id}
          emailThreads={filteredEmailThreads}
          selectedTab={tab}
          receivedLink={[
            '/analyst/:exerciseId/emails/:tab',
            { params: { exerciseId, tab: EmailSelection.RECEIVED } },
          ]}
          sentLink={[
            '/analyst/:exerciseId/emails/:tab',
            { params: { exerciseId, tab: EmailSelection.SENT } },
          ]}
          selectedEmailThread={filteredEmailThreads.find(
            emailThread => emailThread.id === threadId
          )}
          onClick={emailThread =>
            nav('/analyst/:exerciseId/emails/:tab/:threadId', {
              params: { exerciseId, tab, threadId: emailThread.id },
            })
          }
          inAnalyst
          inInstructor
          allowComposing={false}
          composeButtonTitle='Composing is not allowed in the analyst view'
          allowReplying={false}
          replyButtonTitle='Replying is not allowed in the analyst view'
          allowForwarding={false}
          forwardButtonTitle='Forwarding is not allowed in the analyst view'
        />
      </div>
    </div>
  )
}

export default Emails
