import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { api } from './index'
import * as interconnect from './interconnect'

export function useUser(enabled = true) {
  return useQuery({
    queryKey: ['user'],
    queryFn: () => api.auth.me(),
    retry: false,
    staleTime: 5 * 60 * 1000,
    enabled,
  })
}

export function useLogin() {
  const qc = useQueryClient()
  return useMutation({
    mutationFn: (data: { username: string; password: string }) => api.auth.login(data),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['user'] })
    },
  })
}

export function useLogout() {
  const qc = useQueryClient()
  return useMutation({
    mutationFn: () => api.auth.logout(),
    onSuccess: () => {
      qc.clear()
    },
  })
}

export function useStats() {
  return useQuery({
    queryKey: ['stats'],
    queryFn: () => api.dashboard.stats(),
    refetchInterval: 10000,
  })
}

export function useSentence() {
  return useQuery({
    queryKey: ['sentence'],
    queryFn: () => api.dashboard.sentence(),
    staleTime: 24 * 60 * 60 * 1000,
  })
}

export function useSendStats(days?: number) {
  return useQuery({
    queryKey: ['sendStats', days],
    queryFn: async () => {
      const data = await api.dashboard.sendStats(days)
      return Array.isArray(data) ? data : []
    },
  })
}

export function useTaskStats(days?: number) {
  return useQuery({
    queryKey: ['taskStats', days],
    queryFn: async () => {
      const data = await api.dashboard.taskStats(days)
      return Array.isArray(data) ? data : []
    },
  })
}

export function useMonitorStats() {
  return useQuery({
    queryKey: ['monitor'],
    queryFn: () => api.settings.getMonitor(),
    refetchInterval: 5000,
  })
}

export function useTasks(params?: Parameters<typeof api.tasks.list>[0]) {
  return useQuery({
    queryKey: ['tasks', params],
    queryFn: async () => {
      const data = await api.tasks.list(params)
      return {
        ...data,
        data: Array.isArray(data?.data) ? data.data : [],
        total: data?.total ?? 0,
      }
    },
  })
}

export function useTaskTags() {
  return useQuery({
    queryKey: ['taskTags'],
    queryFn: () => api.tasks.tags(),
  })
}

export function useCreateTask() {
  const qc = useQueryClient()
  return useMutation({
    mutationFn: api.tasks.create,
    onSuccess: () => qc.invalidateQueries({ queryKey: ['tasks'] }),
  })
}

export function useUpdateTask() {
  const qc = useQueryClient()
  return useMutation({
    mutationFn: ({ id, data }: { id: string; data: any }) => api.tasks.update(id, data),
    onSuccess: () => qc.invalidateQueries({ queryKey: ['tasks'] }),
  })
}

export function useDeleteTask() {
  const qc = useQueryClient()
  return useMutation({
    mutationFn: (id: string) => api.tasks.delete(id),
    onSuccess: () => qc.invalidateQueries({ queryKey: ['tasks'] }),
  })
}

export function useExecuteTask() {
  const qc = useQueryClient()
  return useMutation({
    mutationFn: (id: string) => api.tasks.execute(id),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['tasks'] })
      qc.invalidateQueries({ queryKey: ['logs'] })
      qc.invalidateQueries({ queryKey: ['stats'] })
    },
  })
}

export function useLogs(params?: Parameters<typeof api.logs.list>[0]) {
  return useQuery({
    queryKey: ['logs', params],
    queryFn: () => api.logs.list(params),
    refetchInterval: 5000,
  })
}

export function useLogDetail(id: string) {
  return useQuery({
    queryKey: ['log', id],
    queryFn: () => api.logs.get(id),
    enabled: !!id,
  })
}

export function useEnvs(params?: Parameters<typeof api.env.list>[0]) {
  return useQuery({
    queryKey: ['envs', params],
    queryFn: () => api.env.list(params),
  })
}

export function useEnvTags() {
  return useQuery({
    queryKey: ['envTags'],
    queryFn: () => api.env.tags(),
  })
}

export function useCreateEnv() {
  const qc = useQueryClient()
  return useMutation({
    mutationFn: api.env.create,
    onSuccess: () => qc.invalidateQueries({ queryKey: ['envs'] }),
  })
}

export function useUpdateEnv() {
  const qc = useQueryClient()
  return useMutation({
    mutationFn: ({ id, data }: { id: string; data: any }) => api.env.update(id, data),
    onSuccess: () => qc.invalidateQueries({ queryKey: ['envs'] }),
  })
}

export function useDeleteEnv() {
  const qc = useQueryClient()
  return useMutation({
    mutationFn: (id: string) => api.env.delete(id),
    onSuccess: () => qc.invalidateQueries({ queryKey: ['envs'] }),
  })
}

export function useFileTree() {
  return useQuery({
    queryKey: ['fileTree'],
    queryFn: () => api.files.tree(),
  })
}

export function useAgents() {
  return useQuery({
    queryKey: ['agents'],
    queryFn: () => api.agents.list(),
    refetchInterval: 10000,
  })
}

export function useAgentTokens() {
  return useQuery({
    queryKey: ['agentTokens'],
    queryFn: () => api.agents.listTokens(),
  })
}

export function useMiseList() {
  return useQuery({
    queryKey: ['mise'],
    queryFn: () => api.mise.list(),
  })
}

export function useDeps(params?: Parameters<typeof api.deps.list>[0]) {
  return useQuery({
    queryKey: ['deps', params],
    queryFn: () => api.deps.list(params),
  })
}

export function useNotifyChannels() {
  return useQuery({
    queryKey: ['notifyChannels'],
    queryFn: () => api.notify.getChannels(),
  })
}

export function useNotifyBindings() {
  return useQuery({
    queryKey: ['notifyBindings'],
    queryFn: () => api.notify.getBindings(),
  })
}

export function useNotifyTypes() {
  return useQuery({
    queryKey: ['notifyTypes'],
    queryFn: () => api.notify.getTypes(),
  })
}

export function useAppLogs(params?: Parameters<typeof api.appLogs.list>[0]) {
  return useQuery({
    queryKey: ['appLogs', params],
    queryFn: async () => {
      const data = await api.appLogs.list(params)
      return {
        ...data,
        data: Array.isArray(data?.data) ? data.data : [],
        total: data?.total ?? 0,
      }
    },
  })
}

export function useSiteSettings() {
  return useQuery({
    queryKey: ['siteSettings'],
    queryFn: () => api.settings.getSite(),
  })
}

export function usePublicSite() {
  return useQuery({
    queryKey: ['publicSite'],
    queryFn: () => api.settings.getPublicSite(),
    staleTime: 5 * 60 * 1000,
    retry: false,
    refetchOnWindowFocus: false,
  })
}

export function useSchedulerSettings() {
  return useQuery({
    queryKey: ['schedulerSettings'],
    queryFn: () => api.settings.getScheduler(),
  })
}

export function useAbout() {
  return useQuery({
    queryKey: ['about'],
    queryFn: () => api.settings.getAbout(),
  })
}

export function useNodes() {
  return useQuery({
    queryKey: ['nodes'],
    queryFn: () => interconnect.getNodes(),
    refetchInterval: 15000,
  })
}

export function useCreateNode() {
  const qc = useQueryClient()
  return useMutation({
    mutationFn: interconnect.createNode,
    onSuccess: () => qc.invalidateQueries({ queryKey: ['nodes'] }),
  })
}

export function useDeleteNode() {
  const qc = useQueryClient()
  return useMutation({
    mutationFn: interconnect.deleteNode,
    onSuccess: () => qc.invalidateQueries({ queryKey: ['nodes'] }),
  })
}

export function useTerminalCmds() {
  return useQuery({
    queryKey: ['terminalCmds'],
    queryFn: () => api.terminal.cmds(),
  })
}

export function useInstallStatus() {
  return useQuery({
    queryKey: ['installStatus'],
    queryFn: async () => {
      const res = await fetch('/api/v1/install/status', { credentials: 'include' })
      if (!res.ok) throw new Error('获取安装状态失败')
      return res.json() as Promise<{ installed: boolean; has_admin?: boolean; message?: string }>
    },
    retry: false,
  })
}

export function useInstall() {
  return useMutation({
    mutationFn: async (data: Record<string, any>) => {
      const res = await fetch('/api/v1/install', {
        method: 'POST',
        credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(data),
      })
      const json = await res.json()
      if (!res.ok) throw new Error(json.error || json.msg || '安装失败')
      return json
    },
  })
}
