import { Button, ButtonGroup, Card } from '@blueprintjs/core'
import { css } from '@emotion/css'
import { notify } from '@inject/shared/notification/engine'
import type { FC } from 'react'
import { memo, useCallback } from 'react'
import EmailAddressForm from '../EmailAddressForm'
import EmailTemplateFormDialog from '../EmailTemplateFormDialog'
import EmailTemplates from '../EmailTemplates'
import { deleteEmailAddress } from '../indexeddb/operations'
import type { EmailAddressInfo } from '../indexeddb/types'

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

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

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

interface EmailAddressProps {
  emailAddress: EmailAddressInfo
}

const EmailAddressItem: FC<EmailAddressProps> = ({ emailAddress }) => {
  const handleDeleteButton = useCallback(
    async (emailAddressInfo: EmailAddressInfo) => {
      try {
        await deleteEmailAddress(emailAddressInfo.id)
      } catch (err) {
        notify(
          `Failed to delete email address '${emailAddressInfo.address}': ${err}`,
          {
            intent: 'danger',
          }
        )
      }
    },
    [notify]
  )

  return (
    <Card style={{ flexDirection: 'column' }}>
      <div className={emailCard}>
        <span className={emailCardName}>{emailAddress.address}</span>
        <ButtonGroup>
          <EmailAddressForm
            emailAddressInfo={emailAddress}
            buttonProps={{
              minimal: true,
              icon: 'edit',
              style: { marginRight: '1rem' },
            }}
          />
          <Button
            minimal
            icon='cross'
            onClick={() => handleDeleteButton(emailAddress)}
          />
        </ButtonGroup>
      </div>
      <div className={emailTemplates}>
        <EmailTemplates emailAddressId={Number(emailAddress.id)} />
        <EmailTemplateFormDialog
          emailAddressId={Number(emailAddress.id)}
          buttonProps={{
            minimal: true,
            text: 'Add template',
            alignText: 'left',
            icon: 'plus',
            style: { padding: '1rem', width: '100%' },
          }}
        />
      </div>
    </Card>
  )
}

export default memo(EmailAddressItem)
