import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { documentsApi } from '../api/endpoints'
import type { DocumentListResponse, DocumentCategoriesResponse } from '../api/types'

interface UseDocumentsParams {
  status?: string
  category?: string
  limit?: number
  offset?: number
}

export const useDocuments = (params: UseDocumentsParams = {}) => {
  const queryClient = useQueryClient()

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

  const uploadMutation = useMutation({
    mutationFn: ({ file, groupKey, category }: { file: File; groupKey?: string; category?: string }) =>
      documentsApi.upload(file, { groupKey, category }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['documents'] })
      queryClient.invalidateQueries({ queryKey: ['categories'] })
    },
  })

  const updateGroupKeyMutation = useMutation({
    mutationFn: ({ documentId, groupKey }: { documentId: string; groupKey: string | null }) =>
      documentsApi.updateGroupKey(documentId, groupKey),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['documents'] })
    },
  })

  const batchUploadMutation = useMutation({
    mutationFn: ({ files, csvFile }: { files: File[]; csvFile?: File }) =>
      documentsApi.batchUpload(files, csvFile),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['documents'] })
    },
  })

  const deleteMutation = useMutation({
    mutationFn: (documentId: string) => documentsApi.delete(documentId),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['documents'] })
    },
  })

  const updateStatusMutation = useMutation({
    mutationFn: ({ documentId, status }: { documentId: string; status: string }) =>
      documentsApi.updateStatus(documentId, status),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['documents'] })
    },
  })

  const triggerAutoLabelMutation = useMutation({
    mutationFn: (documentId: string) => documentsApi.triggerAutoLabel(documentId),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['documents'] })
    },
  })

  const updateCategoryMutation = useMutation({
    mutationFn: ({ documentId, category }: { documentId: string; category: string }) =>
      documentsApi.updateCategory(documentId, category),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['documents'] })
      queryClient.invalidateQueries({ queryKey: ['categories'] })
    },
  })

  return {
    documents: data?.documents || [],
    total: data?.total || 0,
    limit: data?.limit || params.limit || 20,
    offset: data?.offset || params.offset || 0,
    isLoading,
    error,
    refetch,
    uploadDocument: uploadMutation.mutate,
    uploadDocumentAsync: uploadMutation.mutateAsync,
    isUploading: uploadMutation.isPending,
    batchUpload: batchUploadMutation.mutate,
    batchUploadAsync: batchUploadMutation.mutateAsync,
    isBatchUploading: batchUploadMutation.isPending,
    deleteDocument: deleteMutation.mutate,
    isDeleting: deleteMutation.isPending,
    updateStatus: updateStatusMutation.mutate,
    isUpdatingStatus: updateStatusMutation.isPending,
    triggerAutoLabel: triggerAutoLabelMutation.mutate,
    isTriggeringAutoLabel: triggerAutoLabelMutation.isPending,
    updateGroupKey: updateGroupKeyMutation.mutate,
    updateGroupKeyAsync: updateGroupKeyMutation.mutateAsync,
    isUpdatingGroupKey: updateGroupKeyMutation.isPending,
    updateCategory: updateCategoryMutation.mutate,
    updateCategoryAsync: updateCategoryMutation.mutateAsync,
    isUpdatingCategory: updateCategoryMutation.isPending,
  }
}

export const useCategories = () => {
  const { data, isLoading, error, refetch } = useQuery<DocumentCategoriesResponse>({
    queryKey: ['categories'],
    queryFn: () => documentsApi.getCategories(),
    staleTime: 60000,
  })

  return {
    categories: data?.categories || [],
    total: data?.total || 0,
    isLoading,
    error,
    refetch,
  }
}
