// useSpreadsheets Hook - Lógica de negócio para planilhas

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

export const useSpreadsheets = (filters = {}) => {
  const [data, setData] = useState([]);
  const [stats, setStats] = useState(null);
  const [loading, setLoading] = useState(true);
  const [importing, setImporting] = useState(false);
  const [error, setError] = useState(null);

  const fetchData = useCallback(async () => {
    try {
      setLoading(true);
      const spreadsheetData = await spreadsheetsService.getSpreadsheetData(filters);
      setData(spreadsheetData);
      
      const statsData = await spreadsheetsService.getStats();
      setStats(statsData);
      
      setError(null);
    } catch (err) {
      setError(err.message);
      console.error('Erro ao buscar dados:', err);
    } finally {
      setLoading(false);
    }
  }, [JSON.stringify(filters)]);

  const importSpreadsheet = useCallback(async (importData) => {
    try {
      setImporting(true);
      const result = await spreadsheetsService.importSpreadsheet(importData);
      await fetchData(); // Refresh
      return result;
    } catch (err) {
      console.error('Erro ao importar:', err);
      throw new Error(`Erro ao importar: ${err.message}`);
    } finally {
      setImporting(false);
    }
  }, [fetchData]);

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

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

  return {
    data,
    stats,
    loading,
    importing,
    error,
    refresh: fetchData,
    importSpreadsheet,
    archiveRow
  };
};
