import {
  addLearningActivity,
  updateLearningActivity,
} from '@/editor/indexeddb/operations'
import type { ButtonProps } from '@blueprintjs/core'
import {
  Button,
  Dialog,
  DialogBody,
  DialogFooter,
  HTMLSelect,
  InputGroup,
  TextArea,
} 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_ACTIVITY_FORM } from '../assets/pageContent/learningObjectives'
import type { LearningActivityInfo } from '../indexeddb/types'
import { LearningActivityType } from '../indexeddb/types'
import { LEARNING_ACTIVITY_TYPES } from '../utils'

interface LearningActivityFormProps {
  learningActivity?: LearningActivityInfo
  learningObjectiveId: number
  buttonProps: ButtonProps
}

const LearningActivityForm: FC<LearningActivityFormProps> = ({
  learningActivity,
  learningObjectiveId,
  buttonProps,
}) => {
  const [isOpen, setIsOpen] = useState(false)
  const [name, setName] = useState<string>('')
  const [description, setDescription] = useState<string>('')
  const [type, setType] = useState<LearningActivityType>(
    LearningActivityType.TOOL
  )

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

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

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

  useEffect(() => {
    setName(learningActivity?.name || '')
    setDescription(learningActivity?.description || '')
    setType(learningActivity?.type || LearningActivityType.TOOL)
  }, [learningActivity])

  return (
    <>
      <Button {...buttonProps} onClick={() => setIsOpen(true)} />
      <Dialog
        isOpen={isOpen}
        onClose={() => setIsOpen(false)}
        icon={learningActivity ? 'edit' : 'plus'}
        title={
          learningActivity ? 'Edit learning activity' : 'New learning activity'
        }
      >
        <DialogBody>
          <TooltipLabel label={LEARNING_ACTIVITY_FORM.name}>
            <InputGroup
              placeholder='Input text'
              value={name}
              onChange={e => setName(e.target.value)}
            />
          </TooltipLabel>
          <TooltipLabel label={LEARNING_ACTIVITY_FORM.description}>
            <TextArea
              value={description}
              style={{
                width: '100%',
                height: '5rem',
                resize: 'none',
                overflowY: 'auto',
              }}
              placeholder='Input text'
              onChange={e => setDescription(e.target.value)}
            />
          </TooltipLabel>
          <TooltipLabel label={LEARNING_ACTIVITY_FORM.channel}>
            <HTMLSelect
              options={LEARNING_ACTIVITY_TYPES}
              value={type}
              onChange={event =>
                setType(event.currentTarget.value as LearningActivityType)
              }
            />
          </TooltipLabel>
        </DialogBody>
        <DialogFooter
          actions={
            learningActivity ? (
              <Button
                disabled={!name}
                onClick={() =>
                  handleUpdateButton({
                    id: learningActivity.id,
                    name,
                    description,
                    type,
                    learningObjectiveId,
                  })
                }
                intent='primary'
                icon='edit'
                text={GENERIC_CONTENT.buttons.save}
              />
            ) : (
              <Button
                disabled={!name}
                onClick={() =>
                  handleAddButton({
                    name,
                    description,
                    type,
                    learningObjectiveId,
                  })
                }
                intent='primary'
                icon='plus'
                text={GENERIC_CONTENT.buttons.add}
              />
            )
          }
        />
      </Dialog>
    </>
  )
}

export default memo(LearningActivityForm)
