import { NumericInput } 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 SaveButtonGroup from '../SaveButtonGroup'
import TooltipCheckbox from '../Tooltips/TooltipCheckbox'
import TooltipLabel from '../Tooltips/TooltipLabel'
import { OVERLAY_FORM } from '../assets/pageContent/injectSpecification'
import {
  addOverlay,
  deleteOverlay,
  getOverlayByInjectInfoId,
  updateOverlay,
} from '../indexeddb/operations'
import type { Overlay } from '../indexeddb/types'

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

const OverlayForm: FC<OverlayFormProps> = ({
  injectInfoId,
  changed,
  onChangedChange,
}) => {
  const overlay = useLiveQuery(
    () => getOverlayByInjectInfoId(injectInfoId),
    [injectInfoId],
    null
  ) as Overlay

  const [enableOverlay, setEnableOverlay] = useState<boolean>(false)
  const [duration, setDuration] = useState<number>(1)

  useEffect(() => {
    setEnableOverlay(overlay !== undefined)
    setDuration(overlay?.duration || 1)
  }, [overlay])

  const update = useCallback(
    async (newOverlay: Overlay | Omit<Overlay, 'id'>) => {
      try {
        if (overlay) {
          if (!enableOverlay) {
            await deleteOverlay(overlay.id)
            return
          }

          await updateOverlay({
            id: overlay.id,
            ...newOverlay,
          })
        } else {
          if (enableOverlay) {
            await addOverlay(newOverlay)
          }
        }
      } catch (err) {
        notify(`Failed to update overlay: ${err}`, {
          intent: 'danger',
        })
      }
    },
    [notify, overlay, enableOverlay]
  )

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

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

  return (
    <div>
      <TooltipCheckbox
        label={OVERLAY_FORM.enableOverlay}
        checkboxProps={{
          checked: enableOverlay,
          onChange: () => setEnableOverlay(!enableOverlay),
        }}
      />
      {enableOverlay && (
        <TooltipLabel label={OVERLAY_FORM.duration}>
          <NumericInput
            placeholder='Input number'
            min={1}
            value={duration}
            onValueChange={(value: number) => setDuration(value)}
          />
        </TooltipLabel>
      )}
      <SaveButtonGroup
        isValid
        handleUpdate={() => handleUpdate()}
        prevPath='/editor/create/inject-specification'
      />
    </div>
  )
}

export default memo(OverlayForm)
