import Toolbar from '@/components/Toolbar'
import { useParams } from '@/router'
import { Button } from '@blueprintjs/core'
import { useState } from 'react'
import { createPortal } from 'react-dom'
import { Outlet } from 'react-router-dom'

const ToolbarPortal = () => {
  const { exerciseId, teamId } = useParams('/instructor/:exerciseId/:teamId')
  const [open, setOpen] = useState(false)

  const portalRef = document.getElementById('toolPanel')
  const toolbarRef = document.getElementById('topnavPortal')
  return (
    <>
      {portalRef &&
        open &&
        createPortal(
          <Toolbar
            exerciseId={exerciseId}
            teamId={teamId}
            disabled
            disabledTitle='Using tools is not allowed in instructor view'
            onClose={() => setOpen(false)}
          />,
          portalRef
        )}
      {toolbarRef &&
        createPortal(
          <Button
            minimal
            onClick={() => setOpen(prev => !prev)}
            icon='info-sign'
          >
            {`${open ? 'Close' : 'Open'} tools`}
          </Button>,
          toolbarRef
        )}
    </>
  )
}

const Layout = () => (
  <>
    <Outlet />
    <ToolbarPortal />
  </>
)

export default Layout
