import {
  focusManager,
  QueryClient,
  useMutation,
  useQuery,
} from "@tanstack/react-query"
import { reportConfigSaveError } from "./config-save-error"
import { tipcClient } from "./tipc-client"

focusManager.setEventListener((handleFocus) => {
  const handler = () => handleFocus()
  window.addEventListener("focus", handler)
  return () => {
    window.removeEventListener("focus", handler)
  }
})

export const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      networkMode: "always",
    },
  },
})

export const SAVED_CONVERSATIONS_QUERY_KEY = ["conversation-history"] as const

// ============================================================================
// Query Hooks
// ============================================================================

export const useMicrophoneStatusQuery = () =>
  useQuery({
    queryKey: ["microphone-status"],
    queryFn: async () => {
      return tipcClient.getMicrophoneStatus()
    },
  })

export const useConfigQuery = () =>
  useQuery({
    queryKey: ["config"],
    queryFn: async () => {
      return tipcClient.getConfig()
    },
  })

export const useConversationHistoryQuery = (enabled: boolean = true) =>
  useQuery({
    queryKey: SAVED_CONVERSATIONS_QUERY_KEY,
    queryFn: async () => {
      const result = await tipcClient.getConversationHistory()
      return result
    },
    enabled,
    refetchOnWindowFocus: false,
  })

export const useConversationQuery = (conversationId: string | null) =>
  useQuery({
    queryKey: ["conversation", conversationId],
    queryFn: async () => {
      if (!conversationId) return null
      const result = await tipcClient.loadConversation({ conversationId })
      return result
    },
    enabled: !!conversationId,
  })

export const useMcpServerStatus = () =>
  useQuery({
    queryKey: ["mcp-server-status"],
    queryFn: async () => {
      return tipcClient.getMcpServerStatus()
    },
  })

export const useMcpInitializationStatus = () =>
  useQuery({
    queryKey: ["mcp-initialization-status"],
    queryFn: async () => {
      return tipcClient.getMcpInitializationStatus()
    },
  })

export const useAvailableModelsQuery = (
  providerId: string,
  enabled: boolean = true,
  presetId?: string,
) =>
  useQuery({
    queryKey:
      providerId === "openai" && presetId
        ? ["available-models", providerId, presetId]
        : ["available-models", providerId],
    queryFn: async () => {
      return tipcClient.fetchAvailableModels({ providerId })
    },
    enabled: enabled && !!providerId,
    staleTime: 5 * 60 * 1000,
    retry: 1,
  })

export const useSaveConversationMutation = () =>
  useMutation({
    mutationFn: async ({ conversation }: { conversation: any }) => {
      await tipcClient.saveConversation({ conversation })
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: SAVED_CONVERSATIONS_QUERY_KEY })
    },
  })

export const useCreateConversationMutation = () =>
  useMutation({
    mutationFn: async ({
      firstMessage,
      role,
    }: {
      firstMessage: string
      role?: "user" | "assistant"
    }) => {
      const result = await tipcClient.createConversation({ firstMessage, role })
      return result
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: SAVED_CONVERSATIONS_QUERY_KEY })
    },
  })

export const useAddMessageToConversationMutation = () =>
  useMutation({
    mutationFn: async ({
      conversationId,
      content,
      role,
      toolCalls,
      toolResults,
    }: {
      conversationId: string
      content: string
      role: "user" | "assistant" | "tool"
      toolCalls?: Array<{ name: string; arguments: any }>
      toolResults?: Array<{ success: boolean; content: string; error?: string }>
    }) => {
      return tipcClient.addMessageToConversation({
        conversationId,
        content,
        role,
        toolCalls,
        toolResults,
      })
    },
    onSuccess: (_, variables) => {
      queryClient.invalidateQueries({
        queryKey: ["conversation", variables.conversationId],
      })
      queryClient.invalidateQueries({ queryKey: SAVED_CONVERSATIONS_QUERY_KEY })
    },
  })

export const useDeleteConversationMutation = () =>
  useMutation({
    mutationFn: async (conversationId: string) => {
      return tipcClient.deleteConversation({ conversationId })
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: SAVED_CONVERSATIONS_QUERY_KEY })
    },
  })

export const useDeleteAllConversationsMutation = () =>
  useMutation({
    mutationFn: async () => {
      return tipcClient.deleteAllConversations()
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: SAVED_CONVERSATIONS_QUERY_KEY })
      queryClient.invalidateQueries({ queryKey: ["conversation"] })
    },
  })

export const useSaveConfigMutation = () =>
  useMutation({
    mutationFn: tipcClient.saveConfig,
    onSuccess() {
      queryClient.invalidateQueries({
        queryKey: ["config"],
      })
    },
    onError: reportConfigSaveError,
  })

export const useUpdateConfigMutation = () =>
  useMutation({
    mutationFn: async ({ config }: { config: any }) => {
      await tipcClient.saveConfig({ config })
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["config"] })
    },
    onError: reportConfigSaveError,
  })

export const useLoadMcpConfigFile = () =>
  useMutation({
    mutationFn: async () => {
      return tipcClient.loadMcpConfigFile()
    },
  })

export const useSaveMcpConfigFile = () =>
  useMutation({
    mutationFn: async ({ config }: { config: any }) => {
      await tipcClient.saveMcpConfigFile({ config })
    },
  })

// ============================================================================
// History-themed aliases for better semantic naming
// ============================================================================

export const useHistoryQuery = useConversationHistoryQuery
export const useHistoryItemQuery = useConversationQuery
export const useDeleteHistoryItemMutation = useDeleteConversationMutation
export const useDeleteAllHistoryMutation = useDeleteAllConversationsMutation

export const useSavedConversationsQuery = useConversationHistoryQuery
export const useSavedConversationQuery = useConversationQuery
export const useDeleteSavedConversationMutation = useDeleteConversationMutation
export const useDeleteAllSavedConversationsMutation = useDeleteAllConversationsMutation
