import { useQueries, useQuery } from 'react-query';

import useFeatureFlag from 'src/hooks/useFeatureFlag';
import { getBubbalooCount } from 'src/services/bubbaloo';
import { BubbleCode } from 'src/types/bubbaloo';
import { FeatureFlags } from 'src/types/featureFlags';

import { serviceManagementKeys } from '../queries';

const STALE_MS = 30_000;

const useBubbalooCount = (bubbleCode: BubbleCode, enabled = true) => {
  const bubblesEnabled = useFeatureFlag(
    FeatureFlags.SERVICE_MANAGEMENT_BUBBLES_ENABLED,
  );
  return useQuery(
    serviceManagementKeys.bubbaloo.count(bubbleCode),
    () => getBubbalooCount(bubbleCode),
    {
      select: response => response.data.count ?? 0,
      enabled: enabled && !!bubblesEnabled,
      staleTime: STALE_MS,
      onError: () => {
        // Best-effort; bubbles are non-critical UI. Avoid global error handler.
      },
    },
  );
};

export const useBubbalooCounts = (
  bubbleCodes: BubbleCode[],
  enabled = true,
) => {
  const bubblesEnabled = useFeatureFlag(
    FeatureFlags.SERVICE_MANAGEMENT_BUBBLES_ENABLED,
  );
  return useQueries(
    bubbleCodes.map(bubbleCode => ({
      queryKey: serviceManagementKeys.bubbaloo.count(bubbleCode),
      queryFn: () => getBubbalooCount(bubbleCode),
      select: (response: Awaited<ReturnType<typeof getBubbalooCount>>) =>
        response.data.count ?? 0,
      enabled: enabled && !!bubblesEnabled,
      staleTime: STALE_MS,
      onError: () => {
        // Best-effort; bubbles are non-critical UI. Avoid global error handler.
      },
    })),
  );
};

type AggregateOpts = {
  isAgent: boolean;
};

type Aggregate = {
  global: number;
  personalSpace: number;
  agentPanel: number;
  isLoading: boolean;
};

export const useBubbalooAggregate = ({ isAgent }: AggregateOpts): Aggregate => {
  const codes: BubbleCode[] = [
    BubbleCode.SM_USER_TASKS,
    BubbleCode.SM_APPROVAL,
    ...(isAgent
      ? [BubbleCode.SM_AGENT_TASKS, BubbleCode.SM_AGENT_SUBTASKS]
      : []),
  ];

  const queries = useBubbalooCounts(codes);
  const isLoading = queries.some(query => query.isLoading);

  const counts = codes.reduce<Record<string, number>>((acc, code, index) => {
    acc[code] = queries[index].data ?? 0;
    return acc;
  }, {});

  const userTasks = counts[BubbleCode.SM_USER_TASKS] ?? 0;
  const approvals = counts[BubbleCode.SM_APPROVAL] ?? 0;
  const agentTasks = counts[BubbleCode.SM_AGENT_TASKS] ?? 0;
  const agentSubtasks = counts[BubbleCode.SM_AGENT_SUBTASKS] ?? 0;

  // Agents manage approvals from the agent panel, not the service portal.
  // Non-agents (collaborators) see approvals as part of their personal space.
  const personalSpace = userTasks + (isAgent ? 0 : approvals);
  const agentPanel = isAgent ? agentTasks + agentSubtasks + approvals : 0;
  const global = personalSpace + agentPanel;

  return { global, personalSpace, agentPanel, isLoading };
};

export default useBubbalooCount;
