import DeleteAlert from '@/exercisepanel/DeleteAlert'
import { Button, ButtonGroup, Classes } from '@blueprintjs/core'
import { css } from '@emotion/css'
import type { Definition } from '@inject/graphql/fragment-types'
import { useTypedMutation } from '@inject/graphql/graphql'
import { DeleteDefinition } from '@inject/graphql/mutations'
import type { FC } from 'react'
import { useState } from 'react'
import LinkButton from '../LinkButton'
import InfoButton from './InfoButton'

const buttonGroup = css`
  .${Classes.BUTTON} {
    /* appear under the table head */
    z-index: 0 !important;
  }
`

interface DefinitionButtonsProps {
  definition: Definition
}

const DefinitionButtons: FC<DefinitionButtonsProps> = ({ definition }) => {
  const [alertOpen, setAlertOpen] = useState(false)

  const { id: definitionId } = definition

  const [{ fetching: loading }, deleteDefinition] =
    useTypedMutation(DeleteDefinition)

  return (
    <>
      <ButtonGroup className={buttonGroup}>
        <LinkButton
          link={[
            '/exercise-panel/definition/:definitionId',
            { params: { definitionId } },
          ]}
          button={{ icon: 'people', fill: true, title: 'Access' }}
        />
        <Button
          type='button'
          active={alertOpen}
          onClick={() => setAlertOpen(true)}
          icon='trash'
          title='Delete'
        />
        <InfoButton definition={definition} />
      </ButtonGroup>

      <DeleteAlert
        open={alertOpen}
        setOpen={setAlertOpen}
        onDelete={() =>
          deleteDefinition({
            definitionId,
          })
        }
        loading={loading}
      >
        <p>Are you sure you want to delete the selected definition?</p>
        <p>
          <b>
            All exercises created from the selected definition will be deleted!
          </b>
        </p>
      </DeleteAlert>
    </>
  )
}

export default DefinitionButtons
