import { useQuery } from '@tanstack/react-query'
import { dashboardApi } from '../api/endpoints'
import type {
  DashboardStatsResponse,
  DashboardActiveModelResponse,
  RecentActivityResponse,
} from '../api/types'

export const useDashboardStats = () => {
  const { data, isLoading, error, refetch } = useQuery<DashboardStatsResponse>({
    queryKey: ['dashboard', 'stats'],
    queryFn: () => dashboardApi.getStats(),
    staleTime: 30000,
    refetchInterval: 60000,
  })

  return {
    stats: data,
    isLoading,
    error,
    refetch,
  }
}

export const useActiveModel = () => {
  const { data, isLoading, error, refetch } = useQuery<DashboardActiveModelResponse>({
    queryKey: ['dashboard', 'active-model'],
    queryFn: () => dashboardApi.getActiveModel(),
    staleTime: 30000,
    refetchInterval: 60000,
  })

  return {
    model: data?.model ?? null,
    runningTraining: data?.running_training ?? null,
    isLoading,
    error,
    refetch,
  }
}

export const useRecentActivity = (limit: number = 10) => {
  const { data, isLoading, error, refetch } = useQuery<RecentActivityResponse>({
    queryKey: ['dashboard', 'activity', limit],
    queryFn: () => dashboardApi.getRecentActivity(limit),
    staleTime: 30000,
    refetchInterval: 60000,
  })

  return {
    activities: data?.activities ?? [],
    isLoading,
    error,
    refetch,
  }
}

export const useDashboard = () => {
  const stats = useDashboardStats()
  const activeModel = useActiveModel()
  const activity = useRecentActivity()

  return {
    stats: stats.stats,
    model: activeModel.model,
    runningTraining: activeModel.runningTraining,
    activities: activity.activities,
    isLoading: stats.isLoading || activeModel.isLoading || activity.isLoading,
    error: stats.error || activeModel.error || activity.error,
    refetch: () => {
      stats.refetch()
      activeModel.refetch()
      activity.refetch()
    },
  }
}
