import { notify } from '@inject/shared/notification/engine'
import { useLiveQuery } from 'dexie-react-hooks'
import { memo, useCallback, useEffect, useState, type FC } from 'react'
import EmailTemplateFormContent from '../EmailTemplateFormContent'
import SaveButtonGroup from '../SaveButtonGroup'
import {
  addEmailTemplate,
  getEmailTemplateByActivityId,
  updateEmailTemplate,
} from '../indexeddb/operations'
import type { EmailTemplate } from '../indexeddb/types'

interface EmailTemplateFormProps {
  learningActivityId: number
}

const EmailTemplateForm: FC<EmailTemplateFormProps> = ({
  learningActivityId,
}) => {
  const template = useLiveQuery(
    () => getEmailTemplateByActivityId(learningActivityId),
    [learningActivityId],
    null
  ) as EmailTemplate

  const [context, setContext] = useState<string>('')
  const [content, setContent] = useState<string>('')
  const [selectedAddressId, setSelectedAddressId] = useState<number>(0)
  const [fileId, setFileId] = useState<number>(0)

  useEffect(() => {
    setContext(template?.context || '')
    setContent(template?.content || '')
    setSelectedAddressId(template?.emailAddressId || 0)
    setFileId(template?.fileId || 0)
  }, [template])

  const handleUpdateButton = useCallback(
    async (newTemplate: EmailTemplate | Omit<EmailTemplate, 'id'>) => {
      try {
        if (template) {
          await updateEmailTemplate({ id: template.id, ...newTemplate })
        } else {
          await addEmailTemplate(newTemplate)
        }
      } catch (err) {
        notify(`Failed to update template: ${err}`, {
          intent: 'danger',
        })
      }
    },
    [notify, template]
  )

  return (
    <div>
      <EmailTemplateFormContent
        context={context}
        content={content}
        emailAddressId={selectedAddressId}
        fileId={fileId}
        onContextChange={(value: string) => setContext(value)}
        onContentChange={(value: string) => setContent(value)}
        onEmailAddressIdChange={(value: number) => setSelectedAddressId(value)}
        onFileIdChange={(value: number) => setFileId(value)}
      />
      <SaveButtonGroup
        isValid
        handleUpdate={() =>
          handleUpdateButton({
            learningActivityId,
            context,
            content,
            emailAddressId: selectedAddressId,
            fileId,
          })
        }
        prevPath='/editor/create/activity-specification'
      />
    </div>
  )
}

export default memo(EmailTemplateForm)
