import { useState } from 'react';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { documentsApi } from '../api/documents.api';
import type { DocumentRecord } from '../types/documents.types';

export function useUploadWithProgress(documentId: string) {
  const qc = useQueryClient();
  const [progress, setProgress] = useState<number>(0);
  const mutation = useMutation({
    mutationFn: (file: File) => documentsApi.uploadWithProgress(documentId, file, setProgress),
    onMutate: async (file) => {
      // Cancel outgoing refetches
      await qc.cancelQueries({ queryKey: ['document', documentId] });
      await qc.cancelQueries({ queryKey: ['documents'] });

      // Snapshot previous values
      const previousDocument = qc.getQueryData(['document', documentId]);
      const previousDocuments = qc.getQueryData(['documents']);

      // Optimistically update with upload in progress state
      const optimisticUpdate = {
        file_name: file.name,
        content_type: file.type,
        file_size: file.size,
        updated_at: new Date().toISOString(),
      };

      // Update individual document
      qc.setQueryData(['document', documentId], (old: DocumentRecord | undefined) => {
        if (!old) return old;
        return { ...old, ...optimisticUpdate };
      });

      // Update documents list
      qc.setQueryData(['documents'], (old: DocumentRecord[] | undefined) => {
        if (!old) return old;
        return old.map(doc =>
          doc.id === documentId ? { ...doc, ...optimisticUpdate } : doc
        );
      });

      return { previousDocument, previousDocuments };
    },
    onSuccess: () => {
      setProgress(0);
      // Refetch to get complete server state
      qc.invalidateQueries({ queryKey: ['document', documentId] });
      qc.invalidateQueries({ queryKey: ['documents'] });
    },
    onError: (_err, _file, context) => {
      setProgress(0);
      // Rollback on error
      if (context?.previousDocument) {
        qc.setQueryData(['document', documentId], context.previousDocument);
      }
      if (context?.previousDocuments) {
        qc.setQueryData(['documents'], context.previousDocuments);
      }
    },
    networkMode: 'offlineFirst',
  });

  return {
    ...mutation,
    progress,
    resetProgress: () => setProgress(0),
  };
}

