import ManagingExerciseList from '@/components/ExerciseList/ManagingExerciseList'
import { Button, Section, SectionCard } from '@blueprintjs/core'
import { useTypedQuery } from '@inject/graphql/graphql'
import { GetDefinitions } from '@inject/graphql/queries'
import { useMemo, useState, type FC } from 'react'
import ExerciseCreator from './ExerciseCreator'

interface ExerciseManagerProps {
  className?: string
}

const ExerciseManager: FC<ExerciseManagerProps> = ({ className }) => {
  const [creatorOpen, setCreatorOpen] = useState(false)

  const [{ data, fetching: loading }] = useTypedQuery({
    query: GetDefinitions,
  })

  const definitions = useMemo(
    () => data?.definitions || [],
    [data?.definitions]
  )
  return (
    <>
      <Section
        title='Exercises'
        rightElement={
          <Button
            loading={loading}
            disabled={definitions.length == 0}
            title={
              definitions.length == 0
                ? 'Upload a definition before creating an exercise'
                : ''
            }
            onClick={event => {
              event.stopPropagation()
              setCreatorOpen(true)
            }}
            active={creatorOpen}
            icon='add'
          >
            Create
          </Button>
        }
      >
        <SectionCard padded>
          <ManagingExerciseList className={className} />
        </SectionCard>
      </Section>

      <ExerciseCreator open={creatorOpen} setOpen={setCreatorOpen} />
    </>
  )
}

export default ExerciseManager
