// useDocuments Hook - Lógica de negócio para documentos

import { useState, useEffect, useCallback } from 'react';
import { documentsService } from '../services/documentsService';

export const useDocuments = (filters = {}) => {
  const [documents, setDocuments] = useState([]);
  const [stats, setStats] = useState(null);
  const [loading, setLoading] = useState(true);
  const [uploading, setUploading] = useState(false);
  const [error, setError] = useState(null);

  const fetchDocuments = useCallback(async () => {
    try {
      setLoading(true);
      const data = await documentsService.getDocuments(filters);
      setDocuments(data);
      
      const statsData = await documentsService.getStats();
      setStats(statsData);
      
      setError(null);
    } catch (err) {
      setError(err.message);
      console.error('Erro ao buscar documentos:', err);
    } finally {
      setLoading(false);
    }
  }, [JSON.stringify(filters)]);

  const uploadDocument = useCallback(async (formData) => {
    try {
      setUploading(true);
      const result = await documentsService.uploadDocument(formData);
      await fetchDocuments(); // Refresh
      return result;
    } catch (err) {
      console.error('Erro ao fazer upload:', err);
      throw new Error(`Erro ao fazer upload: ${err.message}`);
    } finally {
      setUploading(false);
    }
  }, [fetchDocuments]);

  const deleteDocument = useCallback(async (id) => {
    try {
      const result = await documentsService.deleteDocument(id);
      await fetchDocuments(); // Refresh
      return result;
    } catch (err) {
      console.error('Erro ao excluir:', err);
      throw new Error(`Erro ao excluir: ${err.message}`);
    }
  }, [fetchDocuments]);

  useEffect(() => {
    fetchDocuments();
  }, [fetchDocuments]);

  return {
    documents,
    stats,
    loading,
    uploading,
    error,
    refresh: fetchDocuments,
    uploadDocument,
    deleteDocument
  };
};
