import ContentArea from '@/components/ContentArea'
import FileArea from '@/components/FileArea'
import { Button, ButtonGroup, Divider, FormGroup } from '@blueprintjs/core'
import { css } from '@emotion/css'
import { useSendEmail } from '@inject/graphql/mutations/SendEmail.generated'
import { useGetEmailContacts } from '@inject/graphql/queries/GetEmailContacts.generated'
import { useNotifyContext } from '@inject/shared/notification/contexts/NotifyContext'
import notEmpty from '@inject/shared/utils/notEmpty'
import type { FC } from 'react'
import { memo, useCallback } from 'react'
import TraineeHeaderArea from './TraineeHeaderArea'
import { form } from './classes'
import type { EmailFormProps, OnSendEmailInput } from './typing'
import useThreadSubmission from './useThreadSubmission'

const footer = css`
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  gap: 0.5rem;
`

const TraineeEmailForm: FC<EmailFormProps> = ({
  exerciseId,
  emailThread,
  teamId,
  onSuccess,
  formState: {
    senderAddress,
    fileInfo,
    setFileInfo,
    content,
    setContent,
    discardDraft,
    storeDraft,
    selectedContacts,
    setSelectedContacts,
    bccSelectedContacts,
    setBccSelectedContacts,
    subject,
    setSubject,
  },
}) => {
  const [sendEmailMutate, { loading }] = useSendEmail()
  const { notify } = useNotifyContext()

  const { onSend } = useThreadSubmission({
    ...(emailThread
      ? { existingThreadId: emailThread.id }
      : {
          participantAddresses: [...selectedContacts, senderAddress],
          subject,
          bccAddresses: bccSelectedContacts,
        }),
    exerciseId,
    senderAddress,
    content,
    fileId: fileInfo?.id,
    onSendEmail: ({ threadId }: OnSendEmailInput) => {
      sendEmailMutate({
        variables: {
          sendEmailInput: {
            threadId,
            senderAddress,
            content,
            fileId: fileInfo?.id,
          },
        },
        onCompleted: () => {
          discardDraft()
          onSuccess()
        },
        onError: err => {
          notify(err.message, {
            intent: 'danger',
          })
        },
      })
    },
  })

  const { data: emailContacts } = useGetEmailContacts({
    variables: {
      visibleOnly: true,
    },
    fetchPolicy: 'network-only',
  })

  const traineeList = (emailContacts?.emailContacts || []).filter(notEmpty)

  const onDiscard = useCallback(() => {
    discardDraft()
    onSuccess()
  }, [discardDraft, onSuccess])

  const onSave = useCallback(() => {
    storeDraft()
    onSuccess()
  }, [onSuccess, storeDraft])

  return (
    <div className={form}>
      <TraineeHeaderArea
        {...(emailThread
          ? {
              emailThread,
            }
          : {
              selectedContacts,
              setSelectedContacts,
              bccSelectedContacts,
              setBccSelectedContacts,
              subject,
              setSubject,
            })}
        contacts={traineeList}
        teamAddress={senderAddress}
        exerciseId={exerciseId}
      />
      <Divider style={{ margin: '0.5rem 0' }} />

      <ContentArea content={content} setContent={setContent} />

      <Divider style={{ margin: '0.5rem 0' }} />

      <div className={footer}>
        <FileArea
          exerciseId={exerciseId}
          fileInfo={fileInfo}
          setFileInfo={setFileInfo}
          teamId={teamId}
        />

        <FormGroup disabled={loading} style={{ margin: '0' }}>
          <ButtonGroup>
            <Button icon='trash' onClick={onDiscard}>
              Discard
            </Button>
            <Button icon='floppy-disk' onClick={onSave}>
              Save
            </Button>
            <Button
              type='submit'
              rightIcon='send-message'
              onClick={onSend}
              loading={loading}
            >
              Send
            </Button>
          </ButtonGroup>
        </FormGroup>
      </div>
    </div>
  )
}

export default memo(TraineeEmailForm)
