import { Button, ButtonGroup, Card } 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 EmailTemplateFormDialog from '../EmailTemplateFormDialog'
import {
  deleteEmailTemplate,
  getLearningActivityById,
} from '../indexeddb/operations'
import type { EmailTemplate, LearningActivityInfo } from '../indexeddb/types'

interface EmailTemplateProps {
  emailTemplate: EmailTemplate
}

const EmailTemplateItem: FC<EmailTemplateProps> = ({ emailTemplate }) => {
  const activity = useLiveQuery(
    () => getLearningActivityById(emailTemplate.learningActivityId || 0),
    [emailTemplate],
    null
  ) as LearningActivityInfo

  const handleDeleteButton = useCallback(
    async (template: EmailTemplate) => {
      try {
        await deleteEmailTemplate(template.id)
      } catch (err) {
        notify(`Failed to delete template '${template.context}': ${err}`, {
          intent: 'danger',
        })
      }
    },
    [notify]
  )

  return (
    <Card style={{ display: 'flex', justifyContent: 'space-between' }}>
      <span style={{ height: '100%', flexGrow: 1 }}>
        {isEmpty(emailTemplate.context)
          ? `(${activity?.name})`
          : emailTemplate.context}
      </span>
      <ButtonGroup>
        <EmailTemplateFormDialog
          template={emailTemplate}
          emailAddressId={emailTemplate.emailAddressId}
          buttonProps={{
            minimal: true,
            icon: 'edit',
            style: { marginRight: '1rem' },
          }}
        />
        <Button
          minimal
          icon='cross'
          onClick={() => handleDeleteButton(emailTemplate)}
        />
      </ButtonGroup>
    </Card>
  )
}

export default memo(EmailTemplateItem)
