import { useCallback } from "react"
import type { ChatAttachment } from "@qjclaw/shared-types"
import type { SubmitPromptOptions } from "./useChatStreamingController"
import { HOME_CHAT_PROJECT_ID, HOME_EXPERT_SUGGESTION_PROJECT_IDS } from "../../lib/constants"
import { shouldOfferHomeExpertSwitch } from "../../lib/chat-utils"

type ViewMode = "chat" | "experts" | "tasks" | "plugins" | "settings" | "knowledge"

interface ResumePromptOptions {
  skipHomeIntentSuggestion?: boolean
}

interface UsePromptSubmissionDeps {
  canSend: boolean
  viewMode: ViewMode
  sessionScopeProjectId?: string
  prompt: string
  selectedSkillId: string
  defaultSkillId: string
  composerAttachments: ChatAttachment[]
  submitPrompt: (options: SubmitPromptOptions) => Promise<void>
  requestHomeIntentSuggestion: (options: {
    promptText: string
    skillId?: string
    attachments?: ChatAttachment[]
    requireKnownProject?: boolean
    knownProjectIds?: ReadonlySet<string>
  }) => Promise<unknown>
  clearHomeIntentSuggestion: () => void
  setErrorText: (value: string) => void
  normalizeError: (error: unknown) => string
}

export function usePromptSubmission(deps: UsePromptSubmissionDeps) {
  const {
    canSend,
    viewMode,
    sessionScopeProjectId,
    prompt,
    selectedSkillId,
    defaultSkillId,
    composerAttachments,
    submitPrompt,
    requestHomeIntentSuggestion,
    clearHomeIntentSuggestion,
    setErrorText,
    normalizeError
  } = deps

  const sendPrompt = useCallback(async (options?: ResumePromptOptions) => {
    if (!canSend) {
      return
    }

    const skillId = selectedSkillId === defaultSkillId ? undefined : selectedSkillId
    const trimmedPrompt = prompt.trim()
    const attachmentsToSend = composerAttachments.length ? composerAttachments : undefined
    const shouldSuggestExpert = !options?.skipHomeIntentSuggestion
      && viewMode === "chat"
      && sessionScopeProjectId === HOME_CHAT_PROJECT_ID
      && !skillId
      && trimmedPrompt.length > 0
      && shouldOfferHomeExpertSwitch(trimmedPrompt)

    if (shouldSuggestExpert) {
      try {
        const suggestion = await requestHomeIntentSuggestion({
          promptText: trimmedPrompt,
          skillId,
          attachments: attachmentsToSend,
          requireKnownProject: true,
          knownProjectIds: HOME_EXPERT_SUGGESTION_PROJECT_IDS
        })
        if (suggestion) {
          return
        }
      } catch (error) {
        setErrorText(normalizeError(error))
        return
      }
    }

    clearHomeIntentSuggestion()
    await submitPrompt({
      promptText: prompt,
      skillId,
      forcedAttachments: attachmentsToSend
    })
  }, [canSend, clearHomeIntentSuggestion, composerAttachments, defaultSkillId, normalizeError, prompt, requestHomeIntentSuggestion, selectedSkillId, sessionScopeProjectId, setErrorText, submitPrompt, viewMode])

  return { sendPrompt }
}
