import { InputGroup } from '@blueprintjs/core'
import type { EmailParticipant } from '@inject/graphql/fragments/EmailParticipant.generated'
import { type Dispatch, type FC, type SetStateAction } from 'react'
import SenderSelector from '../SenderSelector'

interface InstructorFromElementProps {
  senderList: string[]
  setSenderAddress: Dispatch<SetStateAction<string>>
  senderAddress: string
  contacts: EmailParticipant[]
  selectedContacts?: string[]
  setSelectedContacts?: Dispatch<SetStateAction<string[]>>
}

const InstructorFromElement: FC<InstructorFromElementProps> = ({
  senderList,
  setSenderAddress,
  senderAddress,
  contacts,
  selectedContacts,
  setSelectedContacts,
}) => {
  if (selectedContacts === undefined) {
    // existing thread
    return senderList.length > 1 ? (
      <SenderSelector
        emailContacts={contacts}
        senderList={senderList}
        senderAddress={senderAddress}
        setSenderAddress={setSenderAddress}
      />
    ) : (
      <InputGroup readOnly value={senderAddress} />
    )
  }

  // new thread
  return (
    <SenderSelector
      emailContacts={contacts}
      senderList={contacts
        .filter(contacts => contacts.definitionAddress)
        .map(contact => contact.address)}
      senderAddress={senderAddress}
      onItemSelect={item => {
        setSelectedContacts?.(prev =>
          prev.includes(item) ? prev : [...prev, item]
        )
        setSenderAddress(item)
      }}
    />
  )
}

export default InstructorFromElement
