import { notify } from '@inject/shared/notification/engine'
import { useLiveQuery } from 'dexie-react-hooks'
import { memo, useCallback, useEffect, useState, type FC } from 'react'
import useValidateExpression from '../ExpressionBuilder/useValidateExpression'
import SaveButtonGroup from '../SaveButtonGroup'
import ToolResponseFormContent from '../ToolResponseFormContent'
import {
  addToolResponse,
  getToolResponseByActivityId,
  updateToolResponse,
} from '../indexeddb/operations'
import type { ToolResponse } from '../indexeddb/types'

interface ToolResponseFormProps {
  learningActivityId: number
}

const ToolResponseForm: FC<ToolResponseFormProps> = ({
  learningActivityId,
}) => {
  const response = useLiveQuery(
    () => getToolResponseByActivityId(learningActivityId),
    [learningActivityId],
    null
  ) as ToolResponse

  const [parameter, setParameter] = useState<string>('')
  const [content, setContent] = useState<string>('')
  const [isRegex, setIsRegex] = useState<boolean>(false)
  const [selectedToolId, setSelectedToolId] = useState<number>(0)
  const [fileId, setFileId] = useState<number>(0)
  const [time, setTime] = useState<number>(0)
  const [milestoneCondition, setMilestoneCondition] = useState<number[]>([])
  const { isValid } = useValidateExpression(milestoneCondition)

  useEffect(() => {
    setParameter(response?.parameter || '')
    setContent(response?.content || '')
    setIsRegex(response?.isRegex || false)
    setSelectedToolId(response?.toolId || 0)
    setTime(response?.time || 0)
    setFileId(response?.fileId || 0)
    setMilestoneCondition(response?.milestoneCondition || [])
  }, [response])

  const handleUpdateButton = useCallback(
    async (newResponse: ToolResponse | Omit<ToolResponse, 'id'>) => {
      try {
        if (response) {
          await updateToolResponse({ id: response.id, ...newResponse })
        } else {
          await addToolResponse(newResponse)
        }
      } catch (error) {
        notify(
          `Failed to update tool response: ${error}`,
          JSON.stringify(error),
          {
            intent: 'danger',
          }
        )
      }
    },
    [response]
  )

  return (
    <div>
      <ToolResponseFormContent
        parameter={parameter}
        content={content}
        isRegex={isRegex}
        toolId={selectedToolId}
        fileId={fileId}
        time={time}
        milestoneCondition={response?.milestoneCondition}
        onParameterChange={(value: string) => setParameter(value)}
        onContentChange={(value: string) => setContent(value)}
        onIsRegexChange={(value: boolean) => setIsRegex(value)}
        onToolIdChange={(value: number) => setSelectedToolId(value)}
        onFileIdChange={(value: number) => setFileId(value)}
        onTimeChange={(value: number) => setTime(value)}
        onMilestoneConditionChange={(value: number[]) =>
          setMilestoneCondition(value)
        }
      />
      <SaveButtonGroup
        isValid={isValid}
        handleUpdate={() =>
          handleUpdateButton({
            learningActivityId,
            parameter,
            content,
            isRegex,
            toolId: selectedToolId,
            time,
            fileId,
            milestoneCondition: isValid ? milestoneCondition : [],
          })
        }
        prevPath='/editor/create/activity-specification'
      />
    </div>
  )
}

export default memo(ToolResponseForm)
