import { useTeamStateMap } from '@/clientsettings/vars/teams'
import InstructorTodoLog from '@/instructor/InstructorTodoLog'
import { useParams } from '@/router'
import type { TabId } from '@blueprintjs/core'
import { Tab, Tabs } from '@blueprintjs/core'
import { css } from '@emotion/css'
import { useTypedQuery } from '@inject/graphql/graphql'
import { GetAnalyticsActionLogsFlat } from '@inject/graphql/queries'
import notEmpty from '@inject/shared/utils/notEmpty'
import { useId, useMemo, useState } from 'react'
import { createPortal } from 'react-dom'

const OverviewPage = () => {
  const { exerciseId } = useParams('/instructor/:exerciseId')

  const [{ data }] = useTypedQuery({
    query: GetAnalyticsActionLogsFlat,
    variables: {
      exerciseId,
      newestFirst: true,
    },
    context: useMemo(
      () => ({
        suspense: true,
      }),
      []
    ),
  })
  const actionLogs = useMemo(
    () => data?.analyticsActionLogs?.filter(notEmpty) || [],
    [data?.analyticsActionLogs]
  )
  const TABS_PARENT_ID = useId()

  const [selectedTabId, setSelectedTabId] = useState<TabId>('read')

  const teamStateMap = useTeamStateMap()
  const selectedTeamStates = useMemo(
    () =>
      (Object.values(teamStateMap ?? {}) || [])
        .filter(teamState => teamState.show)
        .map(teamState => teamState.team.id),
    [teamStateMap]
  )

  if (!data) {
    return <p>Loading</p>
  }

  const topnavPortal = document.getElementById('topnavPortal')

  return (
    <>
      {topnavPortal &&
        createPortal(
          <Tabs
            id={TABS_PARENT_ID}
            onChange={setSelectedTabId}
            selectedTabId={selectedTabId}
            className={css`
              padding-right: 1rem;
            `}
          >
            <Tab id='read' title='To-do' />
            <Tab id='notread' title='Done' />
          </Tabs>,
          topnavPortal
        )}
      <InstructorTodoLog
        height='calc(100vh - 49px)'
        actionLogs={null}
        actionLogIds={actionLogs}
        selectedTeams={selectedTeamStates}
        done={selectedTabId === 'notread'}
      />
    </>
  )
}

export default OverviewPage
