import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { docxService } from '../service/docxService';
import { ApiDocument, DocumentProcessRequest, DocumentImportRequest } from '../service/types';

export interface UseDocumentsOptions {
  workspaceId?: string;
  status?: string;
  limit?: number;
  offset?: number;
}

/**
 * Hook for listing and managing documents
 */
export function useDocuments(options: UseDocumentsOptions = {}) {
  const queryClient = useQueryClient();

  const {
    data: documents,
    isLoading,
    error,
    refetch,
  } = useQuery({
    queryKey: ['documents', options],
    queryFn: () => docxService.listDocuments(options),
    select: (data) => data.documents,
  });

  const listMutation = useMutation({
    mutationFn: () => docxService.listDocuments(options),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['documents'] });
    },
  });

  return {
    documents: data || [],
    total: data?.total || 0,
    isLoading,
    error,
    refetch,
    refresh: () => listMutation.mutate(),
  };
}

/**
 * Hook for getting a single document
 */
export function useDocument(docId: number) {
  const queryClient = useQueryClient();

  const {
    data: document,
    isLoading,
    error,
  } = useQuery({
    queryKey: ['document', docId],
    queryFn: () => docxService.getDocument(docId),
    enabled: docId > 0,
  });

  const refetchDocument = () => {
    queryClient.invalidateQueries({ queryKey: ['document', docId] });
    queryClient.invalidateQueries({ queryKey: ['documents'] });
  };

  return {
    document,
    isLoading,
    error,
    refetch: refetchDocument,
  };
}

/**
 * Hook for uploading a document
 */
export function useDocumentUpload() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: ({
      file,
      workspaceId,
      title,
    }: {
      file: File;
      workspaceId?: string;
      title?: string;
    }) => docxService.uploadDocument(file, workspaceId, title),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['documents'] });
    },
  });
}

/**
 * Hook for updating document metadata
 */
export function useDocumentUpdate() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: ({
      docId,
      updates,
    }: {
      docId: number;
      updates: Partial<Pick<ApiDocument, 'title' | 'tags' | 'summary' | 'workspace_id'>>;
    }) => docxService.updateDocument(docId, updates),
    onSuccess: (_, { docId }) => {
      queryClient.invalidateQueries({ queryKey: ['document', docId] });
      queryClient.invalidateQueries({ queryKey: ['documents'] });
    },
  });
}

/**
 * Hook for processing a document (text extraction + AI enhancement)
 */
export function useDocumentProcess() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: ({
      docId,
      options,
    }: {
      docId: number;
      options?: DocumentProcessRequest;
    }) => docxService.processDocument(docId, options),
    onSuccess: (_, { docId }) => {
      queryClient.invalidateQueries({ queryKey: ['document', docId] });
      queryClient.invalidateQueries({ queryKey: ['documents'] });
    },
  });
}

/**
 * Hook for importing document to memo
 */
export function useDocumentImport() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: ({
      docId,
      importOptions,
    }: {
      docId: number;
      importOptions?: Partial<DocumentImportRequest>;
    }) => docxService.importDocument(docId, importOptions),
    onSuccess: (_, { docId }) => {
      queryClient.invalidateQueries({ queryKey: ['document', docId] });
      queryClient.invalidateQueries({ queryKey: ['documents'] });
      // Also invalidate memos since we created a new memo
      queryClient.invalidateQueries({ queryKey: ['memos'] });
    },
  });
}

/**
 * Hook for deleting a document
 */
export function useDocumentDelete() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (docId: number) => docxService.deleteDocument(docId),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['documents'] });
    },
  });
}
