import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { modelsApi } from '../api/endpoints'
import type {
  ModelVersionListResponse,
  ModelVersionDetailResponse,
  ActiveModelResponse,
} from '../api/types'

export const useModels = (params?: {
  status?: string
  limit?: number
  offset?: number
}) => {
  const queryClient = useQueryClient()

  const { data, isLoading, error, refetch } = useQuery<ModelVersionListResponse>({
    queryKey: ['models', params],
    queryFn: () => modelsApi.list(params),
    staleTime: 30000,
  })

  const activateMutation = useMutation({
    mutationFn: (versionId: string) => modelsApi.activate(versionId),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['models'] })
      queryClient.invalidateQueries({ queryKey: ['models', 'active'] })
    },
  })

  const deactivateMutation = useMutation({
    mutationFn: (versionId: string) => modelsApi.deactivate(versionId),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['models'] })
      queryClient.invalidateQueries({ queryKey: ['models', 'active'] })
    },
  })

  const archiveMutation = useMutation({
    mutationFn: (versionId: string) => modelsApi.archive(versionId),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['models'] })
    },
  })

  const deleteMutation = useMutation({
    mutationFn: (versionId: string) => modelsApi.delete(versionId),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['models'] })
    },
  })

  return {
    models: data?.models ?? [],
    total: data?.total ?? 0,
    isLoading,
    error,
    refetch,
    activateModel: activateMutation.mutate,
    activateModelAsync: activateMutation.mutateAsync,
    isActivating: activateMutation.isPending,
    deactivateModel: deactivateMutation.mutate,
    isDeactivating: deactivateMutation.isPending,
    archiveModel: archiveMutation.mutate,
    isArchiving: archiveMutation.isPending,
    deleteModel: deleteMutation.mutate,
    isDeleting: deleteMutation.isPending,
  }
}

export const useModelDetail = (versionId: string | null) => {
  const { data, isLoading, error } = useQuery<ModelVersionDetailResponse>({
    queryKey: ['models', versionId],
    queryFn: () => modelsApi.getDetail(versionId!),
    enabled: !!versionId,
    staleTime: 30000,
  })

  return {
    model: data ?? null,
    isLoading,
    error,
  }
}

export const useActiveModel = () => {
  const { data, isLoading, error } = useQuery<ActiveModelResponse>({
    queryKey: ['models', 'active'],
    queryFn: () => modelsApi.getActive(),
    staleTime: 30000,
  })

  return {
    hasActiveModel: data?.has_active_model ?? false,
    activeModel: data?.model ?? null,
    isLoading,
    error,
  }
}
