import { Button, ButtonGroup, Card, Icon } from '@blueprintjs/core'
import { notify } from '@inject/shared/notification/engine'
import type { FC } from 'react'
import { memo, useCallback } from 'react'
import InjectForm from '../InjectForm'
import { deleteInjectInfo } from '../indexeddb/operations'
import type { InjectInfo } from '../indexeddb/types'
import { getInjectIcon } from '../utils'

interface InjectItemProps {
  inject: InjectInfo
}

const InjectItem: FC<InjectItemProps> = ({ inject }) => {
  const handleDeleteButton = useCallback(
    async (inject: InjectInfo) => {
      try {
        await deleteInjectInfo(inject.id)
      } catch (err) {
        notify(`Failed to delete inject '${inject.name}': ${err}`, {
          intent: 'danger',
        })
      }
    },
    [notify]
  )

  return (
    <Card style={{ display: 'flex', justifyContent: 'space-between' }}>
      <span style={{ height: '100%', flexGrow: 1 }}>
        <Icon icon={getInjectIcon(inject)} style={{ marginRight: '1rem' }} />
        {inject.name}
      </span>
      <ButtonGroup>
        <InjectForm
          inject={inject}
          buttonProps={{
            minimal: true,
            icon: 'edit',
            style: { marginRight: '1rem' },
          }}
        />
        <Button
          minimal
          icon='cross'
          onClick={() => handleDeleteButton(inject)}
        />
      </ButtonGroup>
    </Card>
  )
}

export default memo(InjectItem)
