import { useQuery } from '@tanstack/react-query';
import { config } from '../../config';
import { useAuthStore } from '../../auth/auth-store';
import { useEnvironmentStore } from '../environment-store';
import { useRefreshInterval } from './use-refresh-interval';
import { useInfiniteStream, type UseInfiniteStreamResult } from '../../hooks/useInfiniteStream';

export function useAgents(status?: string, application?: string) {
  const environment = useEnvironmentStore((s) => s.environment);
  const refetchInterval = useRefreshInterval(10_000);
  return useQuery({
    queryKey: ['agents', environment, status, application],
    queryFn: async () => {
      const token = useAuthStore.getState().accessToken;
      const params = new URLSearchParams();
      if (status) params.set('status', status);
      if (application) params.set('application', application);
      const qs = params.toString();
      const res = await fetch(
        `${config.apiBaseUrl}/environments/${encodeURIComponent(environment!)}/agents${qs ? `?${qs}` : ''}`,
        {
          headers: {
            Authorization: `Bearer ${token}`,
            'X-Cameleer-Protocol-Version': '1',
          },
        });
      if (!res.ok) throw new Error('Failed to load agents');
      return res.json();
    },
    enabled: !!environment,
    refetchInterval,
  });
}

export interface AgentEventResponse {
  id: number;
  instanceId: string;
  applicationId: string;
  eventType: string;
  detail: string;
  timestamp: string;
}

interface AgentEventPageResponse {
  data: AgentEventResponse[];
  nextCursor: string | null;
  hasMore: boolean;
}

export interface UseInfiniteAgentEventsArgs {
  appId?: string;
  agentId?: string;
  isAtTop: boolean;
  pageSize?: number;
}

export function useInfiniteAgentEvents(
  args: UseInfiniteAgentEventsArgs,
): UseInfiniteStreamResult<AgentEventResponse> {
  const environment = useEnvironmentStore((s) => s.environment);
  const pageSize = args.pageSize ?? 50;

  return useInfiniteStream<AgentEventResponse>({
    queryKey: ['agents', 'events', 'infinite', environment ?? '', args.appId ?? '', args.agentId ?? '', pageSize],
    enabled: !!environment,
    isAtTop: args.isAtTop,
    fetchPage: async (cursor) => {
      const token = useAuthStore.getState().accessToken;
      const params = new URLSearchParams();
      if (args.appId) params.set('appId', args.appId);
      if (args.agentId) params.set('agentId', args.agentId);
      if (cursor) params.set('cursor', cursor);
      params.set('limit', String(pageSize));
      const res = await fetch(
        `${config.apiBaseUrl}/environments/${encodeURIComponent(environment!)}/agents/events?${params}`,
        {
          headers: {
            Authorization: `Bearer ${token}`,
            'X-Cameleer-Protocol-Version': '1',
          },
        });
      if (!res.ok) throw new Error('Failed to load agent events');
      const page: AgentEventPageResponse = await res.json();
      return { data: page.data, nextCursor: page.nextCursor, hasMore: page.hasMore };
    },
  });
}
