import EmailContactSelector from '@/email/EmailContactSelector'
import EmailTemplates from '@/email/EmailTemplates'
import { Button, InputGroup } from '@blueprintjs/core'
import type { EmailTemplate } from '@inject/graphql/fragments/EmailTemplate.generated'
import type { FileInfo } from '@inject/graphql/fragments/FileInfo.generated'
import notEmpty from '@inject/shared/utils/notEmpty'
import type { Dispatch, FC, SetStateAction } from 'react'
import { useEffect, useMemo, useState } from 'react'
import InstructorFromElement from './InstructorFromElement'
import {
  contactSelector,
  contactSelectorWrapper,
  gridContainer,
  gridItem,
} from './classes'
import type { HeaderAreaProps } from './typing'

type InstructorHeaderAreaProps = HeaderAreaProps & {
  senderList: string[]
  setSenderAddress: Dispatch<SetStateAction<string>>
  setContent: Dispatch<SetStateAction<string>>
  setActivateMilestone: Dispatch<SetStateAction<string>>
  setDeactivateMilestone: Dispatch<SetStateAction<string>>
  setFileInfo: Dispatch<SetStateAction<FileInfo | undefined>>
  template: EmailTemplate | undefined
  setTemplate: Dispatch<SetStateAction<EmailTemplate | undefined>>
  teamId: string
  senderAddress: string
}

const InstructorHeaderArea: FC<InstructorHeaderAreaProps> = ({
  senderAddress,
  emailThread,
  senderList,
  contacts,
  selectedContacts,
  setSelectedContacts,
  bccSelectedContacts,
  setBccSelectedContacts,
  subject,
  setSubject,
  setSenderAddress,
  setContent,
  setActivateMilestone,
  setDeactivateMilestone,
  setFileInfo,
  template,
  setTemplate,
  teamId,
  exerciseId,
}) => {
  const emailThreadParticipants = useMemo(
    () =>
      (emailThread?.participants || [])
        .filter(notEmpty)
        .map(participant => participant.address)
        .filter(address => address !== senderAddress)
        .join(', '),
    [emailThread?.participants, senderAddress]
  )

  useEffect(() => {
    if (senderList && senderList.length === 1) {
      setSenderAddress && setSenderAddress(senderList[0])
    }
    if (senderList && senderList.length === 0) {
      setSenderAddress && setSenderAddress('')
    }
  }, [senderList, setSenderAddress])

  const [bccOpen, setBccOpen] = useState(false)

  return (
    <div className={gridContainer}>
      <div className={gridItem}>From:</div>
      <InstructorFromElement
        selectedContacts={selectedContacts}
        setSelectedContacts={setSelectedContacts}
        senderList={senderList}
        senderAddress={senderAddress}
        setSenderAddress={setSenderAddress}
        contacts={contacts}
      />

      <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={senderList !== undefined}
              exerciseId={exerciseId}
              senderAddress={senderAddress}
            />
          </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={senderList !== undefined}
            exerciseId={exerciseId}
            senderAddress={senderAddress}
          />
        </>
      )}

      <div className={gridItem}>Subject:</div>
      {emailThread ? (
        <InputGroup readOnly value={emailThread.subject} />
      ) : (
        <InputGroup
          placeholder='Add a subject...'
          value={subject || ''}
          onChange={event => setSubject(event.currentTarget.value)}
        />
      )}

      {senderList !== undefined && (
        <>
          <div className={gridItem}>Template:</div>
          <EmailTemplates
            setSenderAddress={setSenderAddress}
            setContent={setContent}
            setActivateMilestone={setActivateMilestone}
            setDeactivateMilestone={setDeactivateMilestone}
            setFileInfo={setFileInfo}
            template={template}
            setTemplate={setTemplate}
            teamId={teamId}
            exerciseId={exerciseId}
            {...(emailThread
              ? { threadId: emailThread.id }
              : { emailAddresses: senderList, setSubject })}
          />
        </>
      )}
    </div>
  )
}

export default InstructorHeaderArea
