import { useHideSidebarValue } from '@/clientsettings/vars/hidesidebar'
import ExitButton from '@/components/ExitButton'
import MoveTimeButton from '@/components/MoveTimeButton'
import type { Section } from '@/components/Sidebar'
import Sidebar from '@/components/Sidebar'
import HideButton from '@/components/Sidebar/HideSidebarButton'
import Status from '@/components/Status'
import InstructorEmailFormOverlay from '@/email/EmailFormOverlay/InstructorEmailFormOverlay'
import useMailToRef from '@/hooks/useMailToRef'
import InstructorInject from '@/instructor/InstructorInject'
import InstructorTeamSelector from '@/instructor/InstructorTeamSelector'
import TeamListVertical from '@/instructor/InstructorTeamSelector/TeamListVertical'
import LearningObjectivesButton from '@/instructor/LearningObjectives/LearningObjectivesButton'
import { useNavigate } from '@/router'
import { NonIdealState, Spinner, SpinnerSize } from '@blueprintjs/core'
import { css, cx } from '@emotion/css'
import CenteredSpinner from '@inject/shared/components/CenteredSpinner'
import ErrorMessage from '@inject/shared/components/ErrorMessage'
import NotificationDropdown from '@inject/shared/notification/NotificationDropdown'
import type { FC } from 'react'
import { Suspense, memo, useMemo } from 'react'
import { Outlet } from 'react-router-dom'
import ChannelButton from '../ChannelButton'
import {
  contentClass,
  sidebarClass,
  sidebarClassCompact,
  viewClass,
} from '../classes'
import MilestonesButton from './MilestoneButton'
import OverviewButton from './OverviewButton'
import TeamOverviewButton from './TeamOverviewButton'
import TeamTabs from './TeamTabs'
import useInstructorViewData from './useInstructorViewData'

interface InstructorViewProps {
  teamId?: string
  exerciseId?: string
}

const InstructorView: FC<InstructorViewProps> = ({ teamId, exerciseId }) => {
  const contentRef = useMailToRef()
  const hideLeftBar = useHideSidebarValue()
  const nav = useNavigate()

  const { loading, error, loopRunning, channels, emailsEnabled } =
    useInstructorViewData({
      exerciseId,
    })

  const stickySections: Section[] = [
    {
      id: 'status',
      node: (
        <div
          className={cx({
            [css`
              display: flex;
              align-items: center;
              justify-content: space-around;
            `]: !hideLeftBar,
          })}
        >
          <Status
            showTime
            small={hideLeftBar}
            exerciseRunning={loopRunning}
            hideLabel={hideLeftBar}
          />
          <NotificationDropdown hideLabel fill={hideLeftBar} />
        </div>
      ),
    },
  ]
  const sections: Section[] = [
    {
      id: 'options',
      name: 'Options',
      node: (
        <>
          <HideButton />
          <OverviewButton hideLabel={hideLeftBar} />
          <MoveTimeButton
            hideLabel={hideLeftBar}
            exerciseId={exerciseId}
            exerciseRunning={loopRunning}
            disabledTitle={
              exerciseId
                ? loopRunning
                  ? undefined
                  : 'The exercise has to be running to move time'
                : 'A team has to be selected to move time'
            }
          />
          {teamId && (
            <InstructorTeamSelector hideLabel={hideLeftBar} teamId={teamId} />
          )}
          <ExitButton hideLabel={hideLeftBar} />
        </>
      ),
    },
    ...(exerciseId && teamId
      ? [
          {
            id: 'teamsettings',
            name: 'Team',
            node: (
              <>
                <TeamOverviewButton
                  exerciseId={exerciseId}
                  teamId={teamId}
                  hideLabel={hideLeftBar}
                />
                <MilestonesButton teamId={teamId} hideLabel={hideLeftBar} />
                <InstructorInject
                  teamId={teamId}
                  exerciseId={exerciseId}
                  hideLabel={hideLeftBar}
                />
                <LearningObjectivesButton
                  teamId={teamId}
                  exerciseId={exerciseId}
                  hideLabel={hideLeftBar}
                />
              </>
            ),
          },
        ]
      : []),
    ...(!teamId
      ? [
          {
            id: 'teams',
            name: 'Teams',
            node: (
              <>
                <InstructorTeamSelector
                  hideLabel={hideLeftBar}
                  teamId={teamId}
                />
                <TeamListVertical hideLabel={hideLeftBar} />
              </>
            ),
          },
        ]
      : []),
    ...(exerciseId && teamId
      ? [
          {
            id: 'channels',
            name: 'Channels',
            node: loading ? (
              <Spinner size={SpinnerSize.SMALL} />
            ) : (
              <>
                {channels.map(channel => (
                  <ChannelButton
                    key={channel.id}
                    channel={channel}
                    exerciseId={exerciseId}
                    linkTo='instructor'
                    teamId={teamId}
                    hideLabel={hideLeftBar}
                  />
                ))}
              </>
            ),
          },
        ]
      : []),
  ]

  const content = useMemo(() => {
    if (loading) {
      return <CenteredSpinner />
    }
    if (error) {
      return (
        <ErrorMessage>
          <h1>Error occurred!</h1>
          <p>{error.message}</p>
        </ErrorMessage>
      )
    }
    if (!loopRunning && (exerciseId || teamId)) {
      return (
        <NonIdealState
          icon='disable'
          title='Exercise not running'
          description='The selected exercise is not running'
        />
      )
    }
    return (
      <Suspense fallback={<CenteredSpinner />}>
        <Outlet />
      </Suspense>
    )
  }, [error, exerciseId, loading, loopRunning, teamId])

  return (
    <>
      {emailsEnabled && teamId && exerciseId && (
        <InstructorEmailFormOverlay teamId={teamId} exerciseId={exerciseId} />
      )}

      <div className={viewClass}>
        <Sidebar
          onClickLogo={
            exerciseId
              ? () => {
                  nav('/instructor/:exerciseId', {
                    params: {
                      exerciseId,
                    },
                  })
                }
              : undefined
          }
          className={cx({
            [sidebarClass]: !hideLeftBar,
            [sidebarClassCompact]: hideLeftBar,
          })}
          position='left'
          sections={sections}
          stickySections={stickySections}
          hideNames={hideLeftBar}
          showLogo
        />

        <div style={{ position: 'relative', width: '100%' }}>
          <div className={contentClass} id='contentView' ref={contentRef}>
            {exerciseId && <TeamTabs />}
            {content}
          </div>
        </div>

        <div id='toolPanel' />
        <div id='rightPanel' />
      </div>
    </>
  )
}

export default memo(InstructorView)
