import EmailContactSelector from '@/email/EmailContactSelector'
import { Button, InputGroup } from '@blueprintjs/core'
import notEmpty from '@inject/shared/utils/notEmpty'
import type { FC } from 'react'
import { useMemo, useState } from 'react'
import {
  contactSelector,
  contactSelectorWrapper,
  gridContainer,
  gridItem,
} from './classes'
import type { HeaderAreaProps } from './typing'

type TraineeHeaderAreaProps = HeaderAreaProps & {
  teamAddress: string
}

const TraineeHeaderArea: FC<TraineeHeaderAreaProps> = ({
  emailThread,
  contacts,
  selectedContacts,
  setSelectedContacts,
  bccSelectedContacts,
  setBccSelectedContacts,
  subject,
  setSubject,
  exerciseId,
  teamAddress,
}) => {
  const emailThreadParticipants = useMemo(
    () =>
      (emailThread?.participants || [])
        .filter(notEmpty)
        .map(participant => participant.address)
        .filter(address => address !== teamAddress)
        .join(', '),
    [emailThread?.participants, teamAddress]
  )

  const [bccOpen, setBccOpen] = useState(false)

  return (
    <div className={gridContainer}>
      <div className={gridItem}>From:</div>
      <InputGroup readOnly value={teamAddress} />

      <div className={gridItem}>To:</div>
      {emailThread ? (
        <InputGroup readOnly value={emailThreadParticipants} />
      ) : (
        <div className={contactSelectorWrapper}>
          <div className={contactSelector}>
            <EmailContactSelector
              placeholder='Add recipients...'
              emailContacts={contacts}
              selectedContacts={selectedContacts}
              setSelectedContacts={setSelectedContacts}
              inInstructor={false}
              exerciseId={exerciseId}
              senderAddress={teamAddress}
            />
          </div>
          <Button
            minimal
            outlined
            active={bccOpen}
            onClick={() => {
              setBccOpen(prev => !prev)
              if (!bccOpen) {
                setBccSelectedContacts([])
              }
            }}
          >
            Bcc
          </Button>
        </div>
      )}
      {!emailThread && bccOpen && (
        <>
          <div className={gridItem}>Bcc:</div>
          <EmailContactSelector
            placeholder='Add blind copy recipients...'
            emailContacts={contacts}
            selectedContacts={bccSelectedContacts}
            setSelectedContacts={setBccSelectedContacts}
            inInstructor={false}
            exerciseId={exerciseId}
            senderAddress={teamAddress}
          />
        </>
      )}
      <div className={gridItem}>Subject:</div>
      {emailThread ? (
        <InputGroup readOnly value={emailThread.subject} />
      ) : (
        <InputGroup
          placeholder='Add a subject...'
          value={subject || ''}
          onChange={event => setSubject(event.currentTarget.value)}
        />
      )}
    </div>
  )
}

export default TraineeHeaderArea
