import { useCallback } from "react"
import type { DesktopApi, ExpertDefinition, WorkspaceSummary } from "@qjclaw/shared-types"
import { EMPTY_SESSION_ID, HOME_CHAT_PROJECT_ID } from "../../lib/constants"
import type { SidebarExpertEntry } from "./ExpertTree"

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

interface UseHomeNavigationDeps {
  desktopApi: DesktopApi
  workspace: WorkspaceSummary | null
  projectActionPending: boolean
  setViewMode: (viewMode: ViewMode | ((current: ViewMode) => ViewMode)) => void
  setActiveProjectSession: (sessionId: string) => void
  setErrorText: (value: string) => void
  setPrompt: (value: string | ((current: string) => string)) => void
  clearSessions: () => void
  clearAllSessionMessages: () => void
  switchProject: (projectId: string) => Promise<void>
  switchProjectPreservingMessages?: (projectId: string) => Promise<void>
  buildShortcutPrompt: (definition: ExpertDefinition) => string
}

export function useHomeNavigation(deps: UseHomeNavigationDeps) {
  const {
    desktopApi,
    workspace,
    projectActionPending,
    setViewMode,
    setActiveProjectSession,
    setErrorText,
    setPrompt,
    clearSessions,
    clearAllSessionMessages,
    switchProject,
    switchProjectPreservingMessages,
    buildShortcutPrompt
  } = deps

  const openHomeChat = useCallback(async (resetConversation = false) => {
    setViewMode("chat")
    if (projectActionPending) {
      return null
    }

    if (workspace?.currentProjectId === HOME_CHAT_PROJECT_ID) {
      if (resetConversation) {
        clearSessions()
        setActiveProjectSession(EMPTY_SESSION_ID)
        clearAllSessionMessages()
      } else {
        const homeSessions = await desktopApi.chat.listSessionsByProject(HOME_CHAT_PROJECT_ID).catch(() => [])
        setActiveProjectSession(homeSessions[0]?.id ?? EMPTY_SESSION_ID)
      }
      return workspace ?? null
    }

    const homeSessions = resetConversation
      ? []
      : await desktopApi.chat.listSessionsByProject(HOME_CHAT_PROJECT_ID).catch(() => [])
    setActiveProjectSession(homeSessions[0]?.id ?? EMPTY_SESSION_ID)
    await (switchProjectPreservingMessages ?? switchProject)(HOME_CHAT_PROJECT_ID)
    return await desktopApi.workspace.getSummary().catch(() => workspace)
  }, [
    clearAllSessionMessages,
    clearSessions,
    desktopApi.chat,
    desktopApi.workspace,
    projectActionPending,
    setActiveProjectSession,
    setViewMode,
    switchProject,
    switchProjectPreservingMessages,
    workspace
  ])

  const activateHomeShortcut = useCallback(async (entry: SidebarExpertEntry) => {
    setErrorText("")
    const nextWorkspace = await openHomeChat(true)
    const starterPrompt = buildShortcutPrompt(entry.definition)
    if (starterPrompt) {
      setPrompt((current) => current.trim().length > 0 ? current : starterPrompt)
    }
    return nextWorkspace
  }, [buildShortcutPrompt, openHomeChat, setErrorText, setPrompt])

  const handleNavSelection = useCallback(async (mode: ViewMode) => {
    if (mode === "chat") {
      await openHomeChat()
      return
    }

    setViewMode(mode)
  }, [openHomeChat, setViewMode])

  return {
    openHomeChat,
    activateHomeShortcut,
    handleNavSelection
  }
}
