import {
  milestonesOpen,
  useMilestonesOpen,
} from '@/clientsettings/vars/milestones'
import Sidebar from '@/components/Sidebar'
import InstructorMilestones from '@/instructor/InstructorMilestones'
import useGetSelectedTeams from '@/instructor/InstructorTeamSelector/useGetSelectedTeams'
import { Button, ButtonGroup } from '@blueprintjs/core'
import { css } from '@emotion/css'
import { useLayoutEffect, useState, type FC } from 'react'
import { createPortal } from 'react-dom'

const MilestonesButton: FC<{
  hideLabel?: boolean
  disabled?: boolean
  teamId?: string
  exerciseId: string
}> = ({ exerciseId, hideLabel, disabled, teamId }) => {
  const open = useMilestonesOpen()

  const portalRef = document.getElementById('rightPanel')
  const teamIds = useGetSelectedTeams(exerciseId).map(team => team.id)

  const [select, setSelect] = useState<null | 'team' | 'selection' | 'all'>(
    null
  )
  const defaultSelect: typeof select = !select
    ? teamId
      ? 'team'
      : 'selection'
    : select
  const selectTeamIds =
    defaultSelect === 'all'
      ? []
      : defaultSelect === 'team' && teamId
        ? [teamId]
        : teamIds

  useLayoutEffect(() => {
    if (select !== null) {
      setSelect(null)
    }
  }, [teamId])

  return (
    <>
      <Button
        disabled={disabled}
        icon='flag'
        alignText='left'
        fill
        minimal
        text={
          hideLabel ? undefined : open ? 'Close milestones' : 'Open milestones'
        }
        onClick={() => milestonesOpen(!milestonesOpen())}
        title={
          disabled
            ? 'A team has to be selected to show milestones'
            : 'Milestones'
        }
      />
      {open &&
        portalRef &&
        createPortal(
          <Sidebar
            position='right'
            className={css`
              width: 22rem;
            `}
            title='Milestones'
            sections={[
              {
                id: 'selectors',
                node: (
                  <ButtonGroup minimal fill>
                    <Button
                      disabled={defaultSelect === 'all'}
                      onClick={() => setSelect('all')}
                    >
                      All
                    </Button>
                    {teamId && (
                      <Button
                        disabled={defaultSelect === 'team'}
                        onClick={() => setSelect('team')}
                      >
                        Team
                      </Button>
                    )}
                    <Button
                      disabled={defaultSelect === 'selection'}
                      onClick={() => setSelect('selection')}
                    >
                      Selected
                    </Button>
                  </ButtonGroup>
                ),
              },
              {
                id: 'reached',
                node: (
                  <InstructorMilestones
                    exerciseId={exerciseId}
                    teamIds={selectTeamIds}
                  />
                ),
              },
            ]}
            onClose={() => milestonesOpen(false)}
          />,
          portalRef
        )}
    </>
  )
}

export default MilestonesButton
