import LinkButton from '@/components/LinkButton'
import DeleteAlert from '@/exercisepanel/DeleteAlert'
import { Button, ButtonGroup, Card } from '@blueprintjs/core'
import { css } from '@emotion/css'
import type { Definition } from '@inject/graphql/fragments/Definition.generated'
import { useDeleteDefinition } from '@inject/graphql/mutations/DeleteDefinition.generated'
import { GetDefinitionsDocument } from '@inject/graphql/queries/GetDefinitions.generated'
import { GetExercisesDocument } from '@inject/graphql/queries/GetExercises.generated'
import { useNotifyContext } from '@inject/shared/notification/contexts/NotifyContext'
import type { FC } from 'react'
import { memo, useState } from 'react'

const card = css`
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  overflow: auto;
`

const buttonGroup = css`
  align-self: flex-end;
`

const title = css`
  overflow: hidden;
  text-overflow: ellipsis;
`

interface DefinitionProps {
  definition: Definition
}

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

  const { id, name } = definition

  const { notify } = useNotifyContext()

  const [deleteDefinition, { loading }] = useDeleteDefinition({
    variables: {
      definitionId: definition.id,
    },
    refetchQueries: [GetDefinitionsDocument, GetExercisesDocument],
    onError: err => {
      notify(err.message, { intent: 'danger' })
    },
  })

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

      <DeleteAlert
        open={alertOpen}
        setOpen={setAlertOpen}
        onDelete={deleteDefinition}
        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 memo(DefinitionComp)
