import SaveButtonGroup from '@/editor/SaveButtonGroup'
import TooltipLabel from '@/editor/Tooltips/TooltipLabel'
import { QUESTIONNAIRE_FORM } from '@/editor/assets/pageContent/injectSpecification'
import { InputGroup } from '@blueprintjs/core'
import { notify } from '@inject/shared/notification/engine'
import { useLiveQuery } from 'dexie-react-hooks'
import { memo, useCallback, useEffect, useState, type FC } from 'react'
import {
  addQuestionnaire,
  getQuestionnaireByInjectInfoId,
  updateQuestionnaire,
} from '../../indexeddb/operations'
import type { Questionnaire } from '../../indexeddb/types'
import QuestionnaireQuestionForm from './QuestionnaireQuestionForm'
import QuestionnaireQuestions from './QuestionnaireQuestions'

interface QuestionnaireFormProps {
  injectInfoId: number
  changed: boolean
  onChangedChange: (value: boolean) => void
}

const QuestionnaireForm: FC<QuestionnaireFormProps> = ({
  injectInfoId,
  changed,
  onChangedChange,
}) => {
  const questionnaire = useLiveQuery(
    () => getQuestionnaireByInjectInfoId(injectInfoId),
    [injectInfoId],
    null
  ) as Questionnaire

  const [title, setTitle] = useState<string>('')

  useEffect(() => {
    setTitle(questionnaire?.title || '')

    if (questionnaire === undefined) {
      addQuestionnaire({ injectInfoId, title: '' })
    }
  }, [questionnaire, injectInfoId])

  const updateInject = useCallback(
    async (newQuestionnaire: Questionnaire | Omit<Questionnaire, 'id'>) => {
      try {
        if (questionnaire) {
          await updateQuestionnaire({
            id: questionnaire.id,
            ...newQuestionnaire,
          })
        } else {
          await addQuestionnaire(newQuestionnaire)
        }
      } catch (error) {
        notify(
          `Failed to update questionnaire: ${error}`,
          JSON.stringify(error),
          {
            intent: 'danger',
          }
        )
      }
    },
    [questionnaire]
  )

  const handleUpdate = useCallback(async () => {
    if (!changed) onChangedChange(true)
    await updateInject({
      injectInfoId,
      title,
    })
    onChangedChange(false)
  }, [changed, injectInfoId, title, updateInject])

  useEffect(() => {
    if (changed) handleUpdate()
  }, [changed, handleUpdate])

  return (
    <div>
      <TooltipLabel label={QUESTIONNAIRE_FORM.title}>
        <InputGroup
          placeholder='Input text'
          value={title}
          onChange={e => setTitle(e.target.value)}
        />
      </TooltipLabel>
      {questionnaire && (
        <>
          <QuestionnaireQuestions questionnaireId={questionnaire.id} />
          <QuestionnaireQuestionForm
            questionnaireId={questionnaire.id}
            buttonProps={{
              minimal: true,
              text: 'Add new question',
              alignText: 'left',
              icon: 'plus',
              style: { padding: '1rem', width: '100%', marginBottom: '1rem' },
            }}
          />
        </>
      )}
      <SaveButtonGroup
        isValid
        handleUpdate={() => handleUpdate()}
        prevPath='/editor/create/inject-specification'
      />
    </div>
  )
}

export default memo(QuestionnaireForm)
