import { OPEN_COMPOSE_EVENT_TYPE } from '@/email/EmailFormOverlay'
import type { ExtendedEmail } from '@/email/typing'
import { Button, ButtonGroup, Classes } from '@blueprintjs/core'
import { css, cx } from '@emotion/css'
import { breakWord } from '@inject/shared/css/textOverflow'
import type { FC, ReactNode } from 'react'
import { getForwardAllContent } from '../getForwardContent'

const wrapper = css`
  display: flex;
  padding: 0.5rem 1rem 0;
`

const heading = css`
  flex: 1;
`

interface ThreadHeaderCardProps {
  title: string
  subtitle?: ReactNode
  allowReplying: boolean
  allowForwarding: boolean
  forwardButtonTitle?: string
  replyButtonTitle?: string
  onReply?: () => void
  emails: ExtendedEmail[]
  subject: string
}

const ThreadHeaderCard: FC<ThreadHeaderCardProps> = ({
  title,
  subtitle = '',
  allowReplying,
  allowForwarding,
  forwardButtonTitle,
  replyButtonTitle,
  emails,
  subject,
  onReply,
}) => (
  <div className={wrapper}>
    <div className={heading}>
      <h6
        className={cx(Classes.HEADING, Classes.SECTION_HEADER_TITLE, breakWord)}
      >
        {title}
      </h6>
      <div className={cx(Classes.TEXT_MUTED, Classes.SECTION_HEADER_SUB_TITLE)}>
        {subtitle}
      </div>
    </div>
    <div className={Classes.SECTION_HEADER_RIGHT}>
      <ButtonGroup minimal>
        {allowReplying && (
          <Button
            intent='primary'
            text='Reply'
            icon='key-enter'
            onClick={onReply}
            title={replyButtonTitle}
          />
        )}
        {allowForwarding && (
          <Button
            text='Forward all'
            rightIcon='nest'
            onClick={() =>
              window.dispatchEvent(
                new CustomEvent(OPEN_COMPOSE_EVENT_TYPE, {
                  detail: {
                    content: getForwardAllContent(emails),
                    subject: `Fwd: ${subject}`,
                  },
                })
              )
            }
            title={forwardButtonTitle}
          />
        )}
      </ButtonGroup>
    </div>
  </div>
)

export default ThreadHeaderCard
