import { Button, ButtonGroup, Card, Icon, Tooltip } from '@blueprintjs/core'
import { css } from '@emotion/css'
import { notify } from '@inject/shared/notification/engine'
import { useLiveQuery } from 'dexie-react-hooks'
import type { FC } from 'react'
import { memo, useCallback } from 'react'
import ToolForm from '../ToolForm'
import ToolResponseFormDialog from '../ToolResponseFormDialog'
import ToolResponses from '../ToolResponses'
import { deleteTool, doesToolHaveResponse } from '../indexeddb/operations'
import type { ToolInfo } from '../indexeddb/types'

const toolCard = css`
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  padding: 0rem 1rem 1rem 0;
`

const toolCardName = css`
  height: 100%;
  flex-grow: 1;
`

const toolResponses = css`
  width: 100%;
  padding-left: 2rem;
`

interface ToolProps {
  tool: ToolInfo
}

const ToolItem: FC<ToolProps> = ({ tool }) => {
  const toolHasResponses = useLiveQuery(
    () => doesToolHaveResponse(tool.id),
    [tool],
    false
  )

  const handleDeleteButton = useCallback(async (toolInfo: ToolInfo) => {
    try {
      await deleteTool(toolInfo.id)
    } catch (error) {
      notify(
        `Failed to delete tool '${toolInfo.name}': ${error}`,
        JSON.stringify(error),
        {
          intent: 'danger',
        }
      )
    }
  }, [])

  return (
    <Card style={{ flexDirection: 'column' }}>
      <div className={toolCard}>
        <span className={toolCardName}>
          {tool.name}
          {!toolHasResponses && (
            <Tooltip content='Every tool has to have at least one tool response'>
              <Icon icon='high-priority' intent='warning' size={20} />
            </Tooltip>
          )}
        </span>
        <ButtonGroup>
          <ToolForm
            toolInfo={tool}
            buttonProps={{
              minimal: true,
              icon: 'edit',
              style: { marginRight: '1rem' },
            }}
          />
          <Button
            minimal
            icon='cross'
            onClick={() => handleDeleteButton(tool)}
          />
        </ButtonGroup>
      </div>
      <div className={toolResponses}>
        <ToolResponses toolId={tool.id} />
        <ToolResponseFormDialog
          toolId={tool.id}
          buttonProps={{
            minimal: true,
            text: 'Add tool response',
            alignText: 'left',
            icon: 'plus',
            style: { padding: '1rem', width: '100%' },
          }}
        />
      </div>
    </Card>
  )
}

export default memo(ToolItem)
