import { Button, ButtonGroup, Card, Icon, Tooltip } from '@blueprintjs/core'
import { notify } from '@inject/shared/notification/engine'
import { useLiveQuery } from 'dexie-react-hooks'
import { isEmpty } from 'lodash'
import type { FC } from 'react'
import { memo, useCallback } from 'react'
import ToolResponseFormDialog from '../ToolResponseFormDialog'
import {
  deleteToolResponse,
  getLearningActivityById,
} from '../indexeddb/operations'
import type { LearningActivityInfo, ToolResponse } from '../indexeddb/types'

interface ToolResponseProps {
  toolResponse: ToolResponse
  isValid: boolean
}

const ToolResponseItem: FC<ToolResponseProps> = ({ toolResponse, isValid }) => {
  const activity = useLiveQuery(
    () => getLearningActivityById(toolResponse.learningActivityId || 0),
    [toolResponse],
    null
  ) as LearningActivityInfo

  const handleDeleteButton = useCallback(
    async (response: ToolResponse) => {
      try {
        await deleteToolResponse(response.id)
      } catch (err) {
        notify(
          `Failed to delete tool response '${response.parameter}': ${err}`,
          {
            intent: 'danger',
          }
        )
      }
    },
    [notify]
  )

  return (
    <Card style={{ display: 'flex', justifyContent: 'space-between' }}>
      <span style={{ height: '100%', flexGrow: 1 }}>
        {isEmpty(toolResponse.parameter)
          ? `(${activity?.name})`
          : toolResponse.parameter}
        {!isValid && (
          <Tooltip content='Incorrect milestone condition'>
            <Icon icon='high-priority' intent='warning' size={20} />
          </Tooltip>
        )}
      </span>
      <ButtonGroup>
        <ToolResponseFormDialog
          response={toolResponse}
          toolId={toolResponse.toolId}
          buttonProps={{
            minimal: true,
            icon: 'edit',
            style: { marginRight: '1rem' },
          }}
        />
        <Button
          minimal
          icon='cross'
          onClick={() => handleDeleteButton(toolResponse)}
        />
      </ButtonGroup>
    </Card>
  )
}

export default memo(ToolResponseItem)
