import {
  addLearningObjective,
  updateLearningObjective,
} from '@/editor/indexeddb/operations'
import type { ButtonProps } from '@blueprintjs/core'
import {
  Button,
  Dialog,
  DialogBody,
  DialogFooter,
  InputGroup,
} from '@blueprintjs/core'
import { notify } from '@inject/shared/notification/engine'
import type { FC } from 'react'
import { memo, useCallback, useEffect, useState } from 'react'
import TooltipLabel from '../Tooltips/TooltipLabel'
import { GENERIC_CONTENT } from '../assets/generalContent'
import { LEARNING_OBJECTIVE_FORM } from '../assets/pageContent/learningObjectives'
import type { LearningObjectiveInfo } from '../indexeddb/types'

interface LearningObjectiveFormProps {
  learningObjective?: LearningObjectiveInfo
  buttonProps: ButtonProps
}

const LearningObjectiveForm: FC<LearningObjectiveFormProps> = ({
  learningObjective,
  buttonProps,
}) => {
  const [isOpen, setIsOpen] = useState(false)
  const [name, setName] = useState<string>('')

  const clearInput = useCallback(() => {
    setName('')
  }, [])

  const handleAddButton = useCallback(
    async (objective: Omit<LearningObjectiveInfo, 'id'>) => {
      try {
        await addLearningObjective(objective)
        clearInput()
        setIsOpen(false)
      } catch (error) {
        notify(
          `Failed to add learning objective '${objective.name}': ${error}`,
          JSON.stringify(error),
          {
            intent: 'danger',
          }
        )
      }
    },
    []
  )

  const handleUpdateButton = useCallback(
    async (objective: LearningObjectiveInfo) => {
      try {
        await updateLearningObjective(objective)
        setIsOpen(false)
      } catch (error) {
        notify(
          `Failed to update learning objective '${objective.name}': ${error}`,
          JSON.stringify(error),
          {
            intent: 'danger',
          }
        )
      }
    },
    []
  )

  useEffect(() => {
    setName(learningObjective?.name || '')
  }, [learningObjective])

  return (
    <>
      <Button {...buttonProps} onClick={() => setIsOpen(true)} />
      <Dialog
        isOpen={isOpen}
        onClose={() => setIsOpen(false)}
        icon={learningObjective ? 'edit' : 'plus'}
        title={
          learningObjective
            ? 'Edit learning objective'
            : 'New learning objective'
        }
      >
        <DialogBody>
          <TooltipLabel label={LEARNING_OBJECTIVE_FORM.name}>
            <InputGroup
              placeholder='Input text'
              value={name}
              onChange={e => setName(e.target.value)}
            />
          </TooltipLabel>
        </DialogBody>
        <DialogFooter
          actions={
            learningObjective ? (
              <Button
                disabled={!name}
                onClick={() =>
                  handleUpdateButton({
                    id: learningObjective.id,
                    name,
                  })
                }
                intent='primary'
                icon='edit'
                text={GENERIC_CONTENT.buttons.save}
              />
            ) : (
              <Button
                disabled={!name}
                onClick={() => handleAddButton({ name })}
                intent='primary'
                icon='plus'
                text={GENERIC_CONTENT.buttons.add}
              />
            )
          }
        />
      </Dialog>
    </>
  )
}

export default memo(LearningObjectiveForm)
