// useMonitoring Hook - Lógica de negócio para monitoramento
// Encapsula toda a lógica de solicitações de liberação

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

export const useMonitoring = (filters = {}) => {
  const [requests, setRequests] = useState([]);
  const [stats, setStats] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  const fetchRequests = useCallback(async () => {
    try {
      setLoading(true);
      const data = await monitoringService.getRequests(filters);
      setRequests(data);
      
      const statsData = await monitoringService.getStats();
      setStats(statsData);
      
      setError(null);
    } catch (err) {
      setError(err.message);
      console.error('Erro ao buscar solicitações:', err);
    } finally {
      setLoading(false);
    }
  }, [JSON.stringify(filters)]);

  const attendRequest = useCallback(async (id, attendedBy) => {
    try {
      const result = await monitoringService.attendRequest(id, attendedBy);
      await fetchRequests(); // Refresh
      return result;
    } catch (err) {
      console.error('Erro ao atender:', err);
      throw new Error(`Erro ao atender: ${err.message}`);
    }
  }, [fetchRequests]);

  const approveRequest = useCallback(async (id, data) => {
    try {
      const result = await monitoringService.approveRequest(id, data);
      await fetchRequests(); // Refresh
      return result;
    } catch (err) {
      console.error('Erro ao aprovar:', err);
      throw new Error(`Erro ao aprovar: ${err.message}`);
    }
  }, [fetchRequests]);

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

  return {
    requests,
    stats,
    loading,
    error,
    refresh: fetchRequests,
    attendRequest,
    approveRequest
  };
};
