import { useState, useCallback, useEffect, useRef } from 'react';
import { AgentDTO, AgentStatsDTO } from '@/types/rh';
import { rhService } from '@/services/rhService';
import { useToast } from './use-toast';

interface UseAgentsOptions {
  autoFetch?: boolean;
  page?: number;
  size?: number;
  sortBy?: string;
  sortDirection?: 'ASC' | 'DESC';
  query?: string;
  status?: string;
  orgUnit?: string;
  position?: string;
  functionalSituation?: string;
  appointmentType?: string;
  ministry?: string;
}

export function useAgents(options: UseAgentsOptions = {}) {
  const {
    autoFetch = true,
    page: initialPage = 0,
    size = 20,
    sortBy = 'matricula',
    sortDirection = 'ASC',
    query: initialQuery = '',
    status,
    orgUnit,
    position,
    functionalSituation,
    appointmentType,
    ministry
  } = options;

  const [agents, setAgents] = useState<AgentDTO[]>([]);
  const [loading, setLoading] = useState(false);
  const [page, setPage] = useState(initialPage);
  const [totalPages, setTotalPages] = useState(0);
  const [totalElements, setTotalElements] = useState(0);
  const [stats, setStats] = useState<AgentStatsDTO | null>(null);
  const [query, setQuery] = useState('');
  const { toast } = useToast();

  // Ref para armazenar os últimos filtros de estatísticas usados
  const lastStatsFiltersRef = useRef<string>('');

  const fetchAgents = useCallback(async () => {
    setLoading(true);
    try {
      const statsFilters = JSON.stringify({ initialQuery, status, ministry, orgUnit, position, functionalSituation, appointmentType });
      const shouldFetchStats = statsFilters !== lastStatsFiltersRef.current;

      const promises: [Promise<PageResponse<AgentDTO>>, Promise<AgentStatsDTO> | null] = [
        rhService.getAgents({
          page,
          size,
          sortBy,
          sortDirection,
          query: initialQuery,
          status,
          orgUnit,
          position,
          functionalSituation,
          appointmentType,
          ministry
        }),
        shouldFetchStats ? rhService.getStats({
          query: initialQuery,
          status,
          ministry,
          orgUnit,
          position,
          functionalSituation,
          appointmentType
        }) : Promise.resolve(null)
      ];

      const [pageResponse, statsResponse] = await Promise.all(promises);

      setAgents(pageResponse.content);
      setTotalPages(pageResponse.totalPages);
      setTotalElements(pageResponse.totalElements);

      if (statsResponse) {
        setStats(statsResponse);
        lastStatsFiltersRef.current = statsFilters;
      }
    } catch (error) {
      console.error('Erro ao buscar agentes:', error);
      toast({
        title: 'Erro',
        description: 'Não foi possível carregar a lista de agentes.',
        variant: 'destructive',
      });
    } finally {
      setLoading(false);
    }
  }, [page, size, sortBy, sortDirection, initialQuery, status, ministry, orgUnit, position, functionalSituation, appointmentType, toast]);

  useEffect(() => {
    if (autoFetch) {
      fetchAgents();
    }
  }, [fetchAgents, autoFetch]);

  const createAgent = async (data: Omit<AgentDTO, 'id'>) => {
    try {
      const newAgent = await rhService.createAgent(data);
      await fetchAgents();
      return newAgent;
    } catch (error) {
      throw error;
    }
  };

  const updateAgent = async (id: string, data: Partial<AgentDTO>) => {
    try {
      const updatedAgent = await rhService.updateAgent(id, data);
      await fetchAgents();
      return updatedAgent;
    } catch (error) {
      throw error;
    }
  };

  const deleteAgent = async (id: string) => {
    try {
      await rhService.deleteAgent(id);
      await fetchAgents();
    } catch (error) {
      throw error;
    }
  };

  return {
    agents,
    loading,
    page,
    totalPages,
    totalElements,
    setPage,
    fetchAgents,
    createAgent,
    updateAgent,
    deleteAgent,
    stats
  };
}
