import {
  milestonesOpen,
  useMilestonesOpen,
} from '@/clientsettings/vars/milestones'
import Sidebar from '@/components/Sidebar'
import InstructorMilestones from '@/instructor/InstructorMilestones'
import { Button } from '@blueprintjs/core'
import type { FC } from 'react'
import { createPortal } from 'react-dom'

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

  const portalRef = document.getElementById('rightPanel')

  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'
        }
      />
      {teamId &&
        open &&
        portalRef &&
        createPortal(
          <Sidebar
            position='right'
            title='Milestones'
            sections={[
              {
                id: 'reached',
                name: 'Reached',
                node: <InstructorMilestones teamId={teamId} reached />,
              },
              {
                id: 'unreached',
                name: 'Unreached',
                node: <InstructorMilestones teamId={teamId} reached={false} />,
              },
            ]}
            onClose={() => milestonesOpen(false)}
          />,
          portalRef
        )}
    </>
  )
}

export default MilestonesButton
