import { useInternalAgents } from "@/lib/agent.query";
import { useChatOpsStatus } from "@/lib/chatops/chatops.query";
import { useIncomingEmailStatus } from "@/lib/chatops/incoming-email.query";
import config from "@/lib/config/config";
import { useConfig } from "@/lib/config/config.query";
import { useLlmProviderApiKeys } from "@/lib/llm-provider-api-keys.query";
import { useReachabilityMode } from "./use-reachability-mode";

export function useTriggerStatuses() {
  const { data: chatOpsProviders, isLoading: chatOpsLoading } =
    useChatOpsStatus();
  const { data: configData, isLoading: featuresLoading } = useConfig();
  const { data: emailStatus, isLoading: emailLoading } =
    useIncomingEmailStatus();
  const { data: chatApiKeys = [], isLoading: apiKeysLoading } =
    useLlmProviderApiKeys();
  const { data: internalAgents, isLoading: agentsLoading } = useInternalAgents({
    enabled: true,
  });

  const hasLlmKey = chatApiKeys.length > 0;
  const [reachabilityMode] = useReachabilityMode();
  // "manual" means the user exposes the instance themselves — trust them.
  const reachable =
    reachabilityMode === "manual" || !!configData?.features.ngrokDomain;
  const isLocalDev =
    configData?.features.isQuickstart || config.environment === "development";

  const msTeams = chatOpsProviders?.find((p) => p.id === "ms-teams");
  const msTeamsActive = isLocalDev
    ? reachable && hasLlmKey && !!msTeams?.configured
    : hasLlmKey && !!msTeams?.configured;

  const slack = chatOpsProviders?.find((p) => p.id === "slack");
  const slackCreds = slack?.credentials as Record<string, string> | undefined;
  const isSlackSocket = (slackCreds?.connectionMode ?? "socket") === "socket";
  const slackActive = isSlackSocket
    ? hasLlmKey && !!slack?.configured
    : isLocalDev
      ? reachable && hasLlmKey && !!slack?.configured
      : hasLlmKey && !!slack?.configured;

  const emailActive =
    !!configData?.features.incomingEmail?.enabled && !!emailStatus?.isActive;

  // A2A surfaces existing agents over the A2A protocol — no provider config
  // step, so it's "active" whenever there's at least one agent to expose.
  const a2aActive = (internalAgents?.length ?? 0) > 0;

  const triggers = [
    { active: msTeamsActive, href: "/messaging-channels/ms-teams" },
    { active: slackActive, href: "/messaging-channels/slack" },
    { active: emailActive, href: "/messaging-channels/email" },
    { active: a2aActive, href: "/messaging-channels/a2a" },
  ] as const;
  const firstActiveHref =
    triggers.find((t) => t.active)?.href ?? triggers[0].href;

  return {
    msTeams: msTeamsActive,
    slack: slackActive,
    email: emailActive,
    a2a: a2aActive,
    firstActiveHref,
    isLoading:
      chatOpsLoading ||
      featuresLoading ||
      emailLoading ||
      apiKeysLoading ||
      agentsLoading,
  };
}
