import {
  Button,
  ButtonGroup,
  NonIdealState,
  Section,
  SectionCard,
} from '@blueprintjs/core'
import Reloader from '@inject/graphql/components/Reloader'
import { useGetDefinitions } from '@inject/graphql/queries/GetDefinitions.generated'
import CardList from '@inject/shared/components/CardList'
import notEmpty from '@inject/shared/utils/notEmpty'
import { useState, type FC } from 'react'
import DefinitionUploader from './DefinitionUploader'
import Definition from './components/Definition'

interface DefinitionManagerProps {
  className?: string
}

const DefinitionManager: FC<DefinitionManagerProps> = ({ className }) => {
  const { data, refetch } = useGetDefinitions()

  const [uploadOpen, setUploadOpen] = useState(false)

  const definitions = (data?.definitions || []).filter(notEmpty)
  return (
    <>
      <Section
        title='Definitions'
        rightElement={
          <ButtonGroup onClick={e => e.stopPropagation()}>
            <Button
              active={uploadOpen}
              onClick={() => {
                setUploadOpen(true)
              }}
              icon='upload'
            >
              Upload
            </Button>
            <Reloader onRefetch={refetch} />
          </ButtonGroup>
        }
      >
        <SectionCard>
          {definitions.length === 0 ? (
            <NonIdealState
              icon='low-voltage-pole'
              title='No definitions found'
              description='There are no definitions to display'
            />
          ) : (
            <CardList className={className}>
              {definitions.map(definition => (
                <Definition key={definition.id} definition={definition} />
              ))}
            </CardList>
          )}
        </SectionCard>
      </Section>

      <DefinitionUploader open={uploadOpen} setOpen={setUploadOpen} />
    </>
  )
}

export default DefinitionManager
