import { useState, useEffect, useCallback } from 'react';
import { AuditLogDTO, PageResponse, PageRequest } from '@/types/backend';
import { api } from '@/services/api';

interface UseAuditLogsOptions extends PageRequest {
  userId?: string;
  module?: string;
  startDate?: string; // ISO 8601
  endDate?: string; // ISO 8601
  autoFetch?: boolean;
}

interface UseAuditLogsReturn {
  logs: AuditLogDTO[];
  loading: boolean;
  error: string | null;
  page: number;
  totalPages: number;
  totalElements: number;
  refetch: () => Promise<void>;
  setPage: (page: number) => void;
}

export function useAuditLogs(options: UseAuditLogsOptions = {}): UseAuditLogsReturn {
  const {
    page: initialPage = 0,
    size = 20,
    sortBy,
    sortDirection = 'DESC',
    userId,
    module,
    startDate,
    endDate,
    autoFetch = true,
  } = options;

  const [logs, setLogs] = useState<AuditLogDTO[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [page, setPage] = useState(initialPage);
  const [totalPages, setTotalPages] = useState(0);
  const [totalElements, setTotalElements] = useState(0);

  const fetchLogs = useCallback(async () => {
    try {
      setLoading(true);
      setError(null);
      
      const params: any = {
        page,
        size,
        sortBy,
        sortDirection,
      };
      
      if (userId) params.userId = userId;
      if (module) params.module = module;
      if (startDate) params.startDate = startDate;
      if (endDate) params.endDate = endDate;
      
      const response: PageResponse<AuditLogDTO> = await api.getPage<AuditLogDTO>(
        '/admin/audit-logs',
        params
      );
      
      setLogs(response.content);
      setTotalPages(response.totalPages);
      setTotalElements(response.totalElements);
    } catch (err: any) {
      const errorMessage =
        err.response?.data?.message ||
        err.message ||
        'Erro ao carregar logs de auditoria';
      setError(errorMessage);
      console.error('Erro ao buscar logs de auditoria:', err);
    } finally {
      setLoading(false);
    }
  }, [page, size, sortBy, sortDirection, userId, module, startDate, endDate]);

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

  return {
    logs,
    loading,
    error,
    page,
    totalPages,
    totalElements,
    refetch: fetchLogs,
    setPage,
  };
}

