import useGetSelectedTeams from '@/instructor/InstructorTeamSelector/useGetSelectedTeams'
import InstructorTodoLog from '@/instructor/InstructorTodoLog'
import { useParams } from '@/router'
import useRightBar from '@/views/InstructorView/useRightNavbar'
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'

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

  const [{ data }] = useTypedQuery({
    query: GetAnalyticsActionLogsFlat,
    variables: {
      exerciseId,
      newestFirst: true,
    },
    context: useMemo(
      () => ({
        suspense: true,
      }),
      []
    ),
  })
  const selectedTeamStates = useGetSelectedTeams(exerciseId)

  const actionLogs = useMemo(
    () => data?.analyticsActionLogs?.filter(notEmpty) || [],
    [data?.analyticsActionLogs]
  )
  const TABS_PARENT_ID = useId()

  const [selectedTabId, setSelectedTabId] = useState<TabId>('read')
  const element = useRightBar(
    <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>
  )

  return (
    <>
      {element}
      <InstructorTodoLog
        height='calc(100vh - 49px)'
        actionLogs={null}
        contextType='exercise'
        actionLogIds={actionLogs}
        selectedTeams={selectedTeamStates.map(team => team.id)}
        done={selectedTabId === 'notread'}
      />
    </>
  )
}

export default OverviewPage
