import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { config } from '../../config';
import { useAuthStore } from '../../auth/auth-store';
import { useRefreshInterval } from './use-refresh-interval';

export interface CatalogRoute {
  routeId: string;
  exchangeCount: number;
  lastSeen: string | null;
  fromEndpointUri: string | null;
  routeState: string | null;
}

export interface CatalogAgent {
  instanceId: string;
  displayName: string;
  state: string;
  tps: number;
}

export interface DeploymentSummary {
  status: string;
  replicas: string;
  version: number;
}

export interface CatalogApp {
  slug: string;
  displayName: string;
  managed: boolean;
  environmentSlug: string;
  health: 'live' | 'stale' | 'dead' | 'offline' | 'running' | 'error';
  healthTooltip: string;
  agentCount: number;
  routes: CatalogRoute[];
  agents: CatalogAgent[];
  exchangeCount: number;
  deployment: DeploymentSummary | null;
}

export function useCatalog(environment?: string, from?: string, to?: string) {
  const refetchInterval = useRefreshInterval(15_000);
  return useQuery({
    queryKey: ['catalog', environment, from, to],
    queryFn: async () => {
      const token = useAuthStore.getState().accessToken;
      const params = new URLSearchParams();
      if (environment) params.set('environment', environment);
      if (from) params.set('from', from);
      if (to) params.set('to', to);
      const qs = params.toString();
      const res = await fetch(`${config.apiBaseUrl}/catalog${qs ? `?${qs}` : ''}`, {
        headers: {
          Authorization: `Bearer ${token}`,
          'X-Cameleer-Protocol-Version': '1',
        },
      });
      if (!res.ok) throw new Error('Failed to load catalog');
      return res.json() as Promise<CatalogApp[]>;
    },
    placeholderData: (prev) => prev,
    refetchInterval,
  });
}

export function useDismissApp() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: async (applicationId: string) => {
      const token = useAuthStore.getState().accessToken;
      const res = await fetch(`${config.apiBaseUrl}/catalog/${applicationId}`, {
        method: 'DELETE',
        headers: {
          Authorization: `Bearer ${token}`,
          'X-Cameleer-Protocol-Version': '1',
        },
      });
      if (res.status === 409) throw new Error('Cannot dismiss — live agents are still connected');
      if (!res.ok) throw new Error(`Failed to dismiss: ${res.status}`);
    },
    onSuccess: (_data, applicationId) => {
      // Optimistically remove from cache before refetch
      qc.setQueriesData<CatalogApp[]>({ queryKey: ['catalog'] }, (old) =>
        old ? old.filter((a) => a.slug !== applicationId) : old
      );
      qc.invalidateQueries({ queryKey: ['catalog'] });
    },
  });
}

export function useRouteMetrics(from?: string, to?: string, appId?: string, environment?: string) {
  const refetchInterval = useRefreshInterval(30_000);
  return useQuery({
    queryKey: ['routes', 'metrics', environment, from, to, appId],
    queryFn: async () => {
      const token = useAuthStore.getState().accessToken;
      const params = new URLSearchParams();
      if (from) params.set('from', from);
      if (to) params.set('to', to);
      if (appId) params.set('appId', appId);
      const res = await fetch(
        `${config.apiBaseUrl}/environments/${encodeURIComponent(environment!)}/routes/metrics?${params}`, {
        headers: {
          Authorization: `Bearer ${token}`,
          'X-Cameleer-Protocol-Version': '1',
        },
      });
      if (!res.ok) throw new Error('Failed to load route metrics');
      return res.json();
    },
    enabled: !!environment,
    placeholderData: (prev: unknown) => prev,
    refetchInterval,
  });
}
