import useEmailThreads from '@/analyst/dataHooks/useEmailThreads'
import ExerciseContext from '@/analyst/ExerciseContext'
import TabButton from '@/analyst/OverflowTabs/TabButton'
import ThreadLogCards, {
  noEmailReceived,
} from '@/email/TeamEmails/ThreadLog/ThreadLogCards'
import type { ExtendedEmailThread } from '@/email/TeamEmails/ThreadLog/typing'
import { useNavigate, useParams } from '@/router'
import {
  Boundary,
  ButtonGroup,
  Classes,
  Colors,
  OverflowList,
  Popover,
} from '@blueprintjs/core'
import { css } from '@emotion/css'
import type { Email, Team } from '@inject/graphql/fragment-types'
import { useContext, useState } from 'react'
import { Outlet } from 'react-router-dom'

const Layout = () => {
  const { threadId } = useParams('/analyst/:exerciseId/emails/:threadId')
  const { exercise } = useContext(ExerciseContext)
  const nav = useNavigate()
  const emailThreadsData = useEmailThreads()
  const [selectedTeam, setSelectedTeam] = useState<Team>(exercise.teams[0])

  const emailThreads: ExtendedEmailThread[] = emailThreadsData
    .filter(emailThread =>
      emailThread.participants.some(
        participant => participant.team?.id === selectedTeam.id
      )
    )
    .map(emailThread => ({
      ...emailThread,
      lastEmailBiased: emailThread.emails.at(0) as Email,
    }))

  const handleClick = (team: Team) => () => {
    setSelectedTeam(team)
    nav('/analyst/:exerciseId/emails', {
      params: {
        exerciseId: exercise.id,
      },
    })
  }

  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 = (team: Team) => (
    <TabButton
      key={team.id}
      active={selectedTeam.id === team.id}
      onClick={handleClick(team)}
    >
      {team.name}
    </TabButton>
  )
  return (
    <>
      <div
        className={css`
          padding-bottom: 0.25rem;
          margin-bottom: 0.25rem;
          border-bottom: 1px solid ${Colors.BLACK}26;
          .bp5-dark & {
            border-bottom-color: ${Colors.WHITE}33;
          }
          display: flex;
        `}
      >
        <OverflowList
          style={{ alignItems: 'center', marginBottom: 8 }}
          collapseFrom={Boundary.END}
          items={exercise.teams}
          overflowRenderer={overflowRenderer}
          visibleItemRenderer={visibleItemRenderer}
        />
      </div>

      <div
        className={css`
          display: grid;
          grid-template-columns: 400px auto;
          height: calc(100vh - 69px);
        `}
      >
        <div
          className={css`
            overflow-y: auto;
            padding-right: 0.5rem;
            border-right: 1px solid ${Colors.BLACK}26;
            .bp5-dark & {
              border-right-color: ${Colors.WHITE}33;
            }
          `}
        >
          <ThreadLogCards
            teamId={selectedTeam.id}
            emailThreads={emailThreads}
            noEmailString={noEmailReceived}
            inAnalyst
            onClick={emailThread => {
              nav('/analyst/:exerciseId/emails/:threadId', {
                params: {
                  exerciseId: exercise.id,
                  threadId: emailThread.id,
                },
              })
            }}
            selectedEmailThreadId={threadId}
          />
        </div>
        <div
          className={css`
            overflow-y: auto;
          `}
        >
          <Outlet />
        </div>
      </div>
    </>
  )
}

export default Layout
