import { useState, useEffect, useMemo, useRef } from "react";
import {
  Settings,
  CheckCircle2,
  Circle,
  Loader2,
  Key,
  ExternalLink,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
import { Alert, AlertDescription } from "@/components/ui/alert";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { useToast } from "@/components/ui/use-toast";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import {
  useTools,
  mapToolToIntegration,
  type ToolInfo,
  type ToolFieldSchema,
} from "@/hooks/useTools";
import { useConfigStore } from "@/store/configStore";
import { getIconForTool } from "./iconMapping";
import { API_BASE_URL, withAgentExecutionScope } from "@/lib/api";
import {
  Integration,
  IntegrationConfig,
  GenericOAuthIntegrationProvider,
  integrationProviders,
  getAllIntegrations,
} from "./integrations/index";
import { EnhancedConfigDialog } from "./EnhancedConfigDialog";
import { FilterSelector } from "@/components/shared/FilterSelector";

const SHARED_ONLY_PROVIDER_IDS = new Set(["spotify", "homeassistant"]);

const titleFromProviderId = (providerId: string) =>
  providerId
    .split(/[_-]+/)
    .filter(Boolean)
    .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
    .join(" ");

const oauthRedirectPlaceholderOrigin = () =>
  new URL(API_BASE_URL || window.location.origin, window.location.origin)
    .origin;

export function Integrations() {
  const { agents, agentPoliciesByAgent } = useConfigStore();
  const [scopeAgentName, setScopeAgentName] = useState<string | null>(null);
  const scopedAgents = useMemo(
    () =>
      agents
        .filter(
          (agent) =>
            agentPoliciesByAgent[agent.id]?.effective_execution_scope != null,
        )
        .sort((a, b) => a.display_name.localeCompare(b.display_name)),
    [agentPoliciesByAgent, agents],
  );
  const selectedScopeAgent = useMemo(
    () => scopedAgents.find((agent) => agent.id === scopeAgentName) ?? null,
    [scopedAgents, scopeAgentName],
  );
  const effectiveScopeAgentName = selectedScopeAgent?.id ?? null;
  const selectedScopePolicy =
    selectedScopeAgent != null
      ? (agentPoliciesByAgent[selectedScopeAgent.id] ?? null)
      : null;
  const selectedExecutionScope =
    selectedScopePolicy?.effective_execution_scope ?? null;
  const selectedScopeLabel = selectedScopePolicy?.scope_label ?? null;
  const hidesSharedOnlyIntegrations =
    selectedScopeAgent !== null &&
    selectedExecutionScope !== null &&
    selectedExecutionScope !== "shared";
  const disablesDashboardCredentialManagement =
    selectedScopeAgent !== null &&
    selectedScopePolicy?.dashboard_credentials_supported === false;

  // Fetch tools from backend
  const {
    tools: backendTools,
    loading: toolsLoading,
    refetch: refetchTools,
    statusAuthoritative,
  } = useTools(effectiveScopeAgentName, selectedExecutionScope);
  const currentScopeKey = useMemo(
    () =>
      [
        effectiveScopeAgentName ?? "shared",
        selectedExecutionScope ?? "unscoped",
        hidesSharedOnlyIntegrations ? "isolated" : "shared",
      ].join(":"),
    [
      effectiveScopeAgentName,
      hidesSharedOnlyIntegrations,
      selectedExecutionScope,
    ],
  );

  // State
  const [integrationsState, setIntegrationsState] = useState<{
    scopeKey: string;
    integrations: Integration[];
  }>({
    scopeKey: "",
    integrations: [],
  });
  const [loading, setLoading] = useState(false);
  const loadRequestIdRef = useRef(0);
  const currentScopeKeyRef = useRef(currentScopeKey);
  currentScopeKeyRef.current = currentScopeKey;
  const isCurrentScope = (scopeKey: string) =>
    currentScopeKeyRef.current === scopeKey;
  const isCurrentLoadRequest = (requestId: number, scopeKey: string) =>
    requestId === loadRequestIdRef.current && isCurrentScope(scopeKey);
  const oauthProviderForIntegration = (integration: Integration) => {
    const provider = integrationProviders[integration.id];
    if (provider) {
      return provider;
    }
    if (integration.setup_type !== "oauth" || !integration.oauth_provider_id) {
      return null;
    }
    return new GenericOAuthIntegrationProvider(
      integration,
      integration.oauth_provider_id,
    );
  };
  const [activeDialog, setActiveDialog] = useState<{
    integrationId: string;
    config: IntegrationConfig;
  } | null>(null);
  const [configDialog, setConfigDialog] = useState<{
    service: string;
    displayName: string;
    description: string;
    configFields: any[];
    isEditing?: boolean;
    docsUrl?: string | null;
    helperText?: string | null;
    icon?: any;
    iconColor?: string;
    useSelectedScope?: boolean;
  } | null>(null);
  const [filterMode, setFilterMode] = useState<
    "all" | "available" | "unconfigured" | "configured"
  >("all");
  const [searchTerm, setSearchTerm] = useState("");
  const { toast } = useToast();

  useEffect(() => {
    if (
      scopeAgentName &&
      !scopedAgents.some((agent) => agent.id === scopeAgentName)
    ) {
      setScopeAgentName(null);
    }
  }, [scopeAgentName, scopedAgents]);

  // Load integrations from providers and backend tools
  useEffect(() => {
    loadIntegrations();
  }, [backendTools, currentScopeKey]);

  const loadIntegrations = async (forceRefresh = false) => {
    const scopeKey = currentScopeKey;
    if (!isCurrentScope(scopeKey)) {
      return;
    }

    const requestId = ++loadRequestIdRef.current;
    setLoading(true);
    try {
      // Optionally refetch tools from backend to get updated statuses
      // This is important after Google OAuth to get the new status for Google tools
      if (forceRefresh) {
        await refetchTools();
        // Return early since refetchTools will trigger this useEffect again via backendTools update
        return;
      }

      const loadedIntegrations: Integration[] = [];
      const scope = {
        agentName: effectiveScopeAgentName,
        executionScope: selectedExecutionScope,
      };
      const providerIds = new Set(Object.keys(integrationProviders));
      const backendToolsByName = new Map<string, ToolInfo>(
        backendTools.map((tool) => [tool.name, tool]),
      );

      // Load special integrations from providers
      for (const provider of getAllIntegrations()) {
        const config = provider.getConfig(scope);
        const providerTool =
          backendToolsByName.get(config.integration.id) ??
          backendTools.find(
            (tool) => tool.auth_provider === config.integration.id,
          );
        if (
          hidesSharedOnlyIntegrations &&
          SHARED_ONLY_PROVIDER_IDS.has(config.integration.id)
        ) {
          continue;
        }
        const status = provider.loadStatus
          ? await provider.loadStatus(scope)
          : {};
        loadedIntegrations.push({
          ...config.integration,
          config_fields:
            providerTool?.config_fields ?? config.integration.config_fields,
          docs_url: providerTool?.docs_url ?? config.integration.docs_url,
          helper_text:
            providerTool?.helper_text ?? config.integration.helper_text,
          dependencies:
            providerTool?.dependencies ?? config.integration.dependencies,
          icon_color: providerTool?.icon_color ?? config.integration.icon_color,
          dashboard_configuration_supported:
            providerTool?.dashboard_configuration_supported ??
            config.integration.dashboard_configuration_supported,
          execution_scope_supported:
            providerTool?.execution_scope_supported ??
            config.integration.execution_scope_supported,
          ...status,
          config_service:
            providerTool?.name ??
            status.config_service ??
            config.integration.config_service,
        });
      }

      const dynamicOAuthProviderIds = new Set(
        backendTools
          .map((tool) => tool.auth_provider)
          .filter(
            (providerId): providerId is string =>
              typeof providerId === "string" &&
              providerId.length > 0 &&
              !providerIds.has(providerId),
          ),
      );
      for (const providerId of dynamicOAuthProviderIds) {
        const providerTool = backendTools.find(
          (tool) => tool.auth_provider === providerId,
        );
        const integration: Integration = {
          id: providerId,
          name: titleFromProviderId(providerId),
          description: `Connect ${titleFromProviderId(providerId)} OAuth for ${providerTool?.display_name ?? "this tool"}.`,
          category: providerTool?.category ?? "productivity",
          icon: getIconForTool(
            providerTool?.icon ?? null,
            providerTool?.icon_color ?? null,
          ),
          icon_color: providerTool?.icon_color ?? null,
          status: "available",
          setup_type: "oauth",
          connected: false,
          config_fields: providerTool?.config_fields ?? null,
          docs_url: providerTool?.docs_url ?? null,
          helper_text: providerTool?.helper_text ?? null,
          dependencies: providerTool?.dependencies ?? null,
          oauth_provider_id: providerId,
          config_service: providerTool?.name,
          dashboard_configuration_supported:
            providerTool?.dashboard_configuration_supported,
          execution_scope_supported: providerTool?.execution_scope_supported,
        };
        const provider = new GenericOAuthIntegrationProvider(
          integration,
          providerId,
        );
        const status = await provider.loadStatus?.(scope);
        loadedIntegrations.push({
          ...integration,
          ...status,
          config_service:
            providerTool?.name ??
            status?.config_service ??
            integration.config_service,
        });
        providerIds.add(providerId);
      }

      // Load backend tools and map them to integrations
      // (excluding those already handled by providers)
      const backendIntegrations = backendTools
        .filter(
          (tool) =>
            !providerIds.has(tool.name) &&
            !(tool.auth_provider && providerIds.has(tool.auth_provider)),
        )
        .filter(
          (tool) =>
            !hidesSharedOnlyIntegrations ||
            tool.execution_scope_supported !== false,
        )
        .map((tool) => {
          const mapped = mapToolToIntegration(tool);
          return {
            ...mapped,
            icon: getIconForTool(tool.icon, tool.icon_color),
            connected: false,
            // Tools with auth_provider show as connected if their status is 'available'
            status:
              tool.auth_provider && tool.status === "available"
                ? "connected"
                : mapped.status,
            auth_provider: tool.auth_provider ?? undefined,
            config_service: tool.name,
          } as Integration & { auth_provider?: string };
        });

      if (!isCurrentLoadRequest(requestId, scopeKey)) {
        return;
      }

      setIntegrationsState({
        scopeKey,
        integrations: [...loadedIntegrations, ...backendIntegrations],
      });
    } catch (error) {
      if (!isCurrentLoadRequest(requestId, scopeKey)) {
        return;
      }
      console.error("Failed to load integrations:", error);
      toast({
        title: "Error",
        description: "Failed to load integrations",
        variant: "destructive",
      });
    } finally {
      if (isCurrentLoadRequest(requestId, scopeKey)) {
        setLoading(false);
      }
    }
  };

  const integrationNeedsDashboardCredentials = (integration: Integration) => {
    return (
      integration.setup_type !== "none" ||
      Boolean(integration.auth_provider) ||
      Boolean(integration.config_fields && integration.config_fields.length > 0)
    );
  };

  const integrationHasScopedOAuthProvider = (integration: Integration) =>
    integration.setup_type === "oauth" &&
    oauthProviderForIntegration(integration) != null &&
    !SHARED_ONLY_PROVIDER_IDS.has(integration.id);

  const blocksScopedDashboardCredentials = (integration: Integration) =>
    disablesDashboardCredentialManagement &&
    integrationNeedsDashboardCredentials(integration) &&
    !integrationHasScopedOAuthProvider(integration);

  const openToolConfigDialog = (integration: Integration) => {
    if (!integration.config_fields || integration.config_fields.length === 0) {
      return false;
    }
    setConfigDialog({
      service: integration.config_service ?? integration.id,
      displayName: integration.name,
      description: integration.description,
      configFields: integration.config_fields,
      isEditing: integration.status === "connected",
      docsUrl: integration.docs_url || null,
      helperText: integration.helper_text || null,
      icon: null,
      iconColor: integration.icon_color || integration.iconColor || undefined,
    });
    return true;
  };

  const openOAuthClientConfigDialog = (integration: Integration) => {
    if (!integration.oauth_client_config_service) {
      return false;
    }
    const hasCustomClientConfig =
      integration.oauth_custom_client_configured === true;
    const configFields: ToolFieldSchema[] = [
      {
        name: "client_id",
        label: "Client ID",
        type: "text",
        required: true,
        placeholder: "your-client-id.apps.googleusercontent.com",
        description: "OAuth app client ID",
      },
      {
        name: "client_secret",
        label: "Client Secret",
        type: "password",
        required: !hasCustomClientConfig,
        requiredWhenFieldChanges: hasCustomClientConfig ? "client_id" : null,
        placeholder: hasCustomClientConfig
          ? "Required when changing Client ID"
          : "OAuth app client secret",
        description: hasCustomClientConfig
          ? "The saved secret is kept for edits that do not change the Client ID."
          : "OAuth app client secret",
      },
    ];
    if (integration.oauth_client_redirect_uri_supported === true) {
      configFields.push({
        name: "redirect_uri",
        label: "Redirect URI",
        type: "text",
        required: false,
        placeholder: `${oauthRedirectPlaceholderOrigin()}/api/oauth/${
          integration.oauth_provider_id ?? integration.id
        }/callback`,
        description: "Optional provider-specific redirect URI",
      });
    }
    setConfigDialog({
      service: integration.oauth_client_config_service,
      displayName: `${integration.name} OAuth Client`,
      description: `Configure the OAuth app client used to connect ${integration.name}.`,
      configFields,
      isEditing: hasCustomClientConfig,
      docsUrl: integration.docs_url || null,
      helperText: null,
      icon: null,
      iconColor: integration.icon_color || integration.iconColor || undefined,
      useSelectedScope: false,
    });
    return true;
  };

  const handleIntegrationAction = async (integration: Integration) => {
    if (blocksScopedDashboardCredentials(integration)) {
      toast({
        title: "Shared-only dashboard configuration",
        description:
          "Dashboard credential setup is only supported for shared deployment credentials.",
        variant: "destructive",
      });
      return;
    }

    // Check if we have a provider for this integration
    const provider = oauthProviderForIntegration(integration);
    const scope = {
      agentName: effectiveScopeAgentName,
      executionScope: selectedExecutionScope,
    };

    if (provider) {
      const config = provider.getConfig(scope);

      // If there's a custom config component, show it in a dialog
      if (config.ConfigComponent) {
        setActiveDialog({ integrationId: integration.id, config });
        return;
      }

      if (
        integration.status === "connected" &&
        openToolConfigDialog(integration)
      ) {
        return;
      }

      if (
        integration.oauth_client_configured === false &&
        openOAuthClientConfigDialog(integration)
      ) {
        return;
      }

      // Otherwise, execute the action directly
      if (config.onAction) {
        setLoading(true);
        try {
          await config.onAction(integration);
          await loadIntegrations(); // Reload status
        } catch (error) {
          toast({
            title: "Action Failed",
            description:
              error instanceof Error
                ? error.message
                : "Failed to perform action",
            variant: "destructive",
          });
        } finally {
          setLoading(false);
        }
      }
    } else if (
      integration.setup_type === "api_key" ||
      integration.setup_type === "oauth" ||
      integration.setup_type === "special" ||
      integration.setup_type === "none"
    ) {
      // Show generic config dialog for tools with config_fields
      if (!openToolConfigDialog(integration)) {
        toast({
          title: "Configuration Error",
          description: `${integration.name} requires configuration but no fields are specified.`,
          variant: "destructive",
        });
      }
    } else {
      // Fallback for integrations without providers yet
      toast({
        title: "Not Implemented",
        description: `${integration.name} integration is not yet implemented.`,
        variant: "destructive",
      });
    }
  };

  const handleDisconnect = async (integration: Integration) => {
    if (blocksScopedDashboardCredentials(integration)) {
      toast({
        title: "Shared-only dashboard configuration",
        description:
          "Dashboard credential editing is only supported for shared deployment credentials.",
        variant: "destructive",
      });
      return;
    }

    const provider = oauthProviderForIntegration(integration);
    const scope = {
      agentName: effectiveScopeAgentName,
      executionScope: selectedExecutionScope,
    };

    setLoading(true);
    try {
      if (provider?.getConfig(scope).onDisconnect) {
        // Use provider's disconnect method if available
        await provider.getConfig(scope).onDisconnect!(integration.id);
      } else {
        // For generic tools, delete credentials via API
        const response = await fetch(
          withAgentExecutionScope(
            `${API_BASE_URL}/api/credentials/${integration.id}`,
            effectiveScopeAgentName,
            selectedExecutionScope,
          ),
          {
            method: "DELETE",
          },
        );

        if (!response.ok) {
          throw new Error("Failed to disconnect");
        }
      }

      // Refetch tools to update status
      await refetchTools();

      toast({
        title: "Disconnected",
        description: `${integration.name} has been disconnected.`,
      });
    } catch (error) {
      toast({
        title: "Disconnect Failed",
        description:
          error instanceof Error ? error.message : "Failed to disconnect",
        variant: "destructive",
      });
    } finally {
      setLoading(false);
    }
  };

  const getActionButton = (integration: Integration) => {
    if (blocksScopedDashboardCredentials(integration)) {
      return (
        <Button disabled variant="outline" size="sm">
          Shared-only config
        </Button>
      );
    }

    // Check if there's a custom action button
    const provider = oauthProviderForIntegration(integration);
    const config = provider?.getConfig({
      agentName: effectiveScopeAgentName,
      executionScope: selectedExecutionScope,
    });

    if (config?.ActionButton) {
      const ActionButton = config.ActionButton;
      return (
        <ActionButton
          integration={integration}
          loading={loading}
          onAction={() => handleIntegrationAction(integration)}
        />
      );
    }

    const canConfigureOAuthClient =
      integration.setup_type === "oauth" &&
      integration.oauth_client_configured === true &&
      integration.oauth_service_account_configured !== true &&
      Boolean(integration.oauth_client_config_service);
    const oauthClientConfigButton = canConfigureOAuthClient ? (
      <Button
        onClick={() => openOAuthClientConfigDialog(integration)}
        disabled={loading}
        variant="outline"
        size="sm"
      >
        <Settings className="h-4 w-4 mr-1" />
        {integration.oauth_custom_client_configured === true
          ? "Edit client"
          : "Use custom client"}
      </Button>
    ) : null;

    // Handle tools with delegated authentication
    const tool = integration;
    if (tool.auth_provider) {
      // Check if the auth provider is connected
      const authProvider = integrations.find(
        (i) => i.id === tool.auth_provider,
      );

      if (
        integration.status === "connected" ||
        integration.status === "available"
      ) {
        // Auth provider is connected
        if (tool.config_fields && tool.config_fields.length > 0) {
          return (
            <div className="flex gap-2 items-center">
              <Badge className="bg-green-500/10 dark:bg-green-500/20 text-green-700 dark:text-green-300">
                <CheckCircle2 className="h-3 w-3 mr-1" />
                Connected
              </Badge>
              <Button
                onClick={() => handleIntegrationAction(integration)}
                disabled={loading}
                variant="outline"
                size="sm"
              >
                <Settings className="h-4 w-4 mr-1" />
                Configure
              </Button>
            </div>
          );
        } else {
          // Tool with no additional config
          return (
            <Badge className="bg-green-500/10 dark:bg-green-500/20 text-green-700 dark:text-green-300">
              <CheckCircle2 className="h-3 w-3 mr-1" />
              Connected
            </Badge>
          );
        }
      } else {
        // Auth provider not connected
        return (
          <div className="flex items-center gap-2">
            <Badge variant="outline" className="text-muted-foreground">
              Requires {authProvider?.name || tool.auth_provider}
            </Badge>
            <Button
              onClick={() => {
                if (authProvider) {
                  handleIntegrationAction(authProvider);
                } else {
                  toast({
                    title: `Connect ${tool.auth_provider} first`,
                    description: `Please connect to ${tool.auth_provider} to use this tool.`,
                  });
                }
              }}
              disabled={loading}
              variant="outline"
              size="sm"
            >
              <ExternalLink className="h-4 w-4 mr-1" />
              Setup
            </Button>
          </div>
        );
      }
    }

    // Tools with no setup required
    if (integration.setup_type === "none") {
      // Check if there are optional config fields
      if (integration.config_fields && integration.config_fields.length > 0) {
        // Check if any configuration has been saved
        const hasConfig = integration.status === "connected";

        if (hasConfig) {
          // Show edit/reset buttons for configured tools
          return (
            <div className="flex gap-2">
              <Button
                onClick={() => handleIntegrationAction(integration)}
                disabled={loading}
                variant="outline"
                size="sm"
              >
                <Settings className="h-4 w-4 mr-1" />
                Settings
              </Button>
              <Button
                onClick={() => handleDisconnect(integration)}
                disabled={loading}
                variant="ghost"
                size="sm"
              >
                Reset
              </Button>
            </div>
          );
        } else {
          // Show optional configure button
          return (
            <div className="flex gap-2 items-center">
              <Badge className="bg-green-500/10 dark:bg-green-500/20 text-green-700 dark:text-green-300">
                <CheckCircle2 className="h-3 w-3 mr-1" />
                Ready
              </Badge>
              <Button
                onClick={() => handleIntegrationAction(integration)}
                disabled={loading}
                variant="outline"
                size="sm"
              >
                <Settings className="h-4 w-4 mr-1" />
                Configure
              </Button>
            </div>
          );
        }
      } else {
        // No config fields, just show ready status
        return (
          <Badge className="bg-green-500/10 dark:bg-green-500/20 text-green-700 dark:text-green-300">
            <CheckCircle2 className="h-3 w-3 mr-1" />
            Ready to Use
          </Badge>
        );
      }
    }

    if (integration.setup_type === "oauth" && integration.status_error) {
      return (
        <div className="flex gap-2 items-center">
          <Button disabled variant="outline" size="sm">
            Status unavailable
          </Button>
          {oauthClientConfigButton}
          <Button
            onClick={() => void loadIntegrations(false)}
            disabled={loading}
            variant="outline"
            size="sm"
          >
            Retry status
          </Button>
        </div>
      );
    }

    if (
      integration.setup_type === "oauth" &&
      integration.status !== "connected" &&
      canConfigureOAuthClient
    ) {
      return (
        <div className="flex gap-2 items-center">
          <Button
            onClick={() => handleIntegrationAction(integration)}
            disabled={loading}
            size="sm"
            className="flex items-center gap-2"
          >
            {loading ? (
              <Loader2 className="h-4 w-4 animate-spin" />
            ) : (
              <ExternalLink className="h-4 w-4" />
            )}
            Connect
          </Button>
          {oauthClientConfigButton}
        </div>
      );
    }

    if (
      integration.setup_type === "oauth" &&
      integration.oauth_client_configured === false &&
      integration.oauth_service_account_configured !== true
    ) {
      return (
        <Button
          onClick={() => handleIntegrationAction(integration)}
          disabled={loading || !integration.oauth_client_config_service}
          variant="outline"
          size="sm"
        >
          Configure client
        </Button>
      );
    }

    // For other connected tools, show Edit/Disconnect
    if (integration.status === "connected") {
      return (
        <div className="flex gap-2">
          <Button
            onClick={() => handleIntegrationAction(integration)}
            disabled={loading}
            variant="outline"
            size="sm"
          >
            Edit
          </Button>
          {oauthClientConfigButton}
          <Button
            onClick={() => handleDisconnect(integration)}
            disabled={loading}
            variant="destructive"
            size="sm"
          >
            Disconnect
          </Button>
        </div>
      );
    }

    const buttonText =
      integration.setup_type === "special"
        ? "Setup"
        : integration.setup_type === "oauth"
          ? "Connect"
          : "Configure";

    const icon =
      integration.setup_type === "special" ? (
        <Settings className="h-4 w-4" />
      ) : integration.setup_type === "oauth" ? (
        <ExternalLink className="h-4 w-4" />
      ) : (
        <Key className="h-4 w-4" />
      );

    return (
      <Button
        onClick={() => handleIntegrationAction(integration)}
        disabled={loading}
        size="sm"
        className="flex items-center gap-2"
      >
        {loading ? <Loader2 className="h-4 w-4 animate-spin" /> : icon}
        {buttonText}
      </Button>
    );
  };

  const IntegrationCard = ({ integration }: { integration: Integration }) => {
    const isConnected = integration.status === "connected";
    const usesGoogleUserData = (
      integration.oauth_provider_id ?? integration.id
    ).startsWith("google_");
    const statusLabel = integration.status_error
      ? "Status error"
      : integration.status === "not_connected"
        ? "Needs setup"
        : "Available";

    return (
      <Card className="h-full hover:shadow-2xl hover:scale-[1.02] hover:-translate-y-1 transition-all duration-300">
        <CardHeader>
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-2">
              {integration.icon}
              <CardTitle className="text-lg">{integration.name}</CardTitle>
            </div>
            {isConnected ? (
              <Badge className="bg-gradient-to-r from-green-500 to-emerald-500 text-white border-0">
                <CheckCircle2 className="h-3 w-3 mr-1" />
                Connected
              </Badge>
            ) : (
              <Badge className="bg-amber-500/10 dark:bg-amber-500/20 text-amber-700 dark:text-amber-300 backdrop-blur-md border-amber-500/20">
                <Circle className="h-3 w-3 mr-1" />
                {statusLabel}
              </Badge>
            )}
          </div>
          <CardDescription>{integration.description}</CardDescription>
          {usesGoogleUserData ? (
            <p className="text-xs text-muted-foreground">
              By connecting, you authorize this MindRoom installation to access
              Google data for the selected agent and credential scope. Shared or
              unscoped agents can use the connected account for any user
              authorized to invoke them. Relevant results may be sent to your
              configured AI model and retained in session or Matrix history. The
              installation operator and anyone with administrative or filesystem
              access may be able to access stored credentials and data. Project
              maintainers have no automatic access merely because they maintain
              MindRoom; if they also operate this installation, they may have
              operator access.{" "}
              <a
                href="https://docs.mindroom.chat/privacy/"
                target="_blank"
                rel="noreferrer"
                className="underline underline-offset-2"
              >
                Privacy policy
              </a>
              .
            </p>
          ) : null}
          {integration.status_error ? (
            <p className="text-xs text-muted-foreground">
              Status error: {integration.status_error}
            </p>
          ) : integration.helper_text ? (
            <p className="text-xs text-muted-foreground">
              {integration.helper_text}
            </p>
          ) : null}
        </CardHeader>

        <CardContent>
          <div className="space-y-3">
            <div className="flex gap-2">{getActionButton(integration)}</div>
          </div>
        </CardContent>
      </Card>
    );
  };

  // Filter integrations
  const integrations =
    integrationsState.scopeKey === currentScopeKey
      ? integrationsState.integrations
      : [];

  const filteredIntegrations = useMemo(() => {
    let filtered = integrations;

    // Filter by mode
    switch (filterMode) {
      case "available":
        filtered = filtered.filter(
          (i) => i.status === "available" || i.status === "connected",
        );
        break;
      case "unconfigured":
        filtered = filtered.filter(
          (i) => i.status !== "connected" && i.setup_type !== "none",
        );
        break;
      case "configured":
        filtered = filtered.filter((i) => i.status === "connected");
        break;
      // 'all' - no filtering needed
    }

    // Filter by search term
    if (searchTerm) {
      filtered = filtered.filter(
        (i) =>
          i.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
          i.description.toLowerCase().includes(searchTerm.toLowerCase()),
      );
    }

    return filtered;
  }, [integrations, filterMode, searchTerm]);

  const categories = useMemo(() => {
    const allCategories = [
      { id: "all", name: "All", count: filteredIntegrations.length },
      {
        id: "email",
        name: "Email & Calendar",
        count: filteredIntegrations.filter((i) => i.category === "email")
          .length,
      },
      {
        id: "communication",
        name: "Communication",
        count: filteredIntegrations.filter(
          (i) => i.category === "communication",
        ).length,
      },
      {
        id: "entertainment",
        name: "Entertainment",
        count: filteredIntegrations.filter(
          (i) => i.category === "entertainment",
        ).length,
      },
      {
        id: "social",
        name: "Social",
        count: filteredIntegrations.filter((i) => i.category === "social")
          .length,
      },
      {
        id: "development",
        name: "Development",
        count: filteredIntegrations.filter((i) => i.category === "development")
          .length,
      },
      {
        id: "research",
        name: "Research",
        count: filteredIntegrations.filter((i) => i.category === "research")
          .length,
      },
      {
        id: "smart_home",
        name: "Smart Home",
        count: filteredIntegrations.filter((i) => i.category === "smart_home")
          .length,
      },
      {
        id: "information",
        name: "Information",
        count: filteredIntegrations.filter((i) => i.category === "information")
          .length,
      },
    ];

    return filterMode !== "all"
      ? allCategories.filter((cat) => cat.count > 0)
      : allCategories;
  }, [filteredIntegrations, filterMode]);

  const getIntegrationsForCategory = (categoryId: string) => {
    if (categoryId === "all") return filteredIntegrations;
    return filteredIntegrations.filter((i) => i.category === categoryId);
  };

  // Show loading state while fetching tools
  if (toolsLoading && integrations.length === 0) {
    return (
      <div className="h-full flex items-center justify-center">
        <div className="text-center">
          <Loader2 className="h-8 w-8 animate-spin mx-auto mb-4" />
          <p className="text-gray-600 dark:text-gray-400">
            Loading available tools...
          </p>
        </div>
      </div>
    );
  }

  return (
    <>
      <div className="h-full overflow-y-auto">
        <div className="mb-4">
          <div className="flex flex-wrap items-center justify-between gap-2 mb-2">
            <h2 className="text-2xl font-bold">Tools</h2>
            <div className="flex flex-wrap items-center gap-2 w-full sm:w-auto">
              <Select
                value={scopeAgentName ?? "shared"}
                onValueChange={(value) =>
                  setScopeAgentName(value === "shared" ? null : value)
                }
              >
                <SelectTrigger className="w-full sm:w-72">
                  <SelectValue placeholder="Shared deployment credentials" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="shared">
                    Shared deployment credentials
                  </SelectItem>
                  {scopedAgents.map((agent) => (
                    <SelectItem key={agent.id} value={agent.id}>
                      {agent.display_name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
              <Input
                type="search"
                placeholder="Search tools..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="w-full sm:w-64"
              />
              <FilterSelector
                options={[
                  { value: "all", label: "Show All" },
                  { value: "available", label: "Available" },
                  { value: "unconfigured", label: "Unconfigured" },
                  { value: "configured", label: "Configured" },
                ]}
                value={filterMode}
                onChange={(value) =>
                  setFilterMode(
                    value as
                      | "all"
                      | "available"
                      | "unconfigured"
                      | "configured",
                  )
                }
                size="sm"
              />
            </div>
          </div>
          <p className="text-gray-600 dark:text-gray-400">
            {selectedScopeAgent
              ? `Configuring tools for ${selectedScopeAgent.display_name} (${
                  selectedScopeLabel ?? "unscoped"
                }).`
              : "Connect external services to enable agent capabilities"}
          </p>
          {hidesSharedOnlyIntegrations && (
            <Alert className="mt-3">
              <AlertDescription>
                Legacy dashboard credential setup, editing, and disconnect are
                only supported for shared deployment credentials.
              </AlertDescription>
              <AlertDescription className="mt-2">
                Home Assistant and Spotify remain shared-only unless the agent
                has an effective shared runtime scope (
                <code>worker_scope=shared</code>). OAuth-backed Google
                integrations can be connected for this selected agent.
              </AlertDescription>
            </Alert>
          )}
          {selectedScopeAgent && statusAuthoritative === false && (
            <Alert className="mt-3">
              <AlertDescription>
                Requester-scoped tool status is preview only. The dashboard can
                show scope support rules and shared env-backed availability, but
                it cannot inspect live requester-owned scoped credentials.
              </AlertDescription>
            </Alert>
          )}
        </div>

        <div className="">
          <Tabs defaultValue="all" className="h-full">
            <TabsList className="flex flex-wrap h-auto gap-1 overflow-visible">
              {categories.map((category) => (
                <TabsTrigger
                  key={category.id}
                  value={category.id}
                  className="text-xs flex-shrink-0"
                >
                  {category.name}
                  {category.count > 0 && (
                    <Badge variant="secondary" className="ml-1 text-xs">
                      {category.count}
                    </Badge>
                  )}
                </TabsTrigger>
              ))}
            </TabsList>

            {categories.map((category) => (
              <TabsContent
                key={category.id}
                value={category.id}
                className="mt-4"
              >
                <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
                  {getIntegrationsForCategory(category.id).map(
                    (integration) => (
                      <IntegrationCard
                        key={integration.id}
                        integration={integration}
                      />
                    ),
                  )}
                </div>
              </TabsContent>
            ))}
          </Tabs>
        </div>
      </div>

      {/* Dynamic Configuration Dialog */}
      {activeDialog && (
        <Dialog
          open={true}
          onOpenChange={(open) => !open && setActiveDialog(null)}
        >
          <DialogContent className="max-w-4xl max-h-[90vh] overflow-auto">
            <DialogHeader>
              <DialogTitle className="flex items-center gap-2">
                {activeDialog.config.integration.icon}
                {activeDialog.config.integration.name} Setup
              </DialogTitle>
              <DialogDescription>
                {activeDialog.config.integration.description}
              </DialogDescription>
            </DialogHeader>
            {activeDialog.config.ConfigComponent && (
              <activeDialog.config.ConfigComponent
                onClose={() => setActiveDialog(null)}
                agentName={effectiveScopeAgentName}
                executionScope={selectedExecutionScope}
                onSuccess={async () => {
                  setActiveDialog(null);
                  // Force refresh to get updated Google tools status
                  await loadIntegrations(true);
                }}
              />
            )}
          </DialogContent>
        </Dialog>
      )}

      {/* Enhanced Configuration Dialog */}
      {configDialog && (
        <EnhancedConfigDialog
          open={true}
          onClose={() => setConfigDialog(null)}
          service={configDialog.service}
          displayName={configDialog.displayName}
          description={configDialog.description}
          configFields={configDialog.configFields}
          isEditing={configDialog.isEditing}
          docsUrl={configDialog.docsUrl}
          helperText={configDialog.helperText}
          icon={configDialog.icon}
          iconColor={configDialog.iconColor}
          agentName={
            configDialog.useSelectedScope === false
              ? null
              : effectiveScopeAgentName
          }
          executionScope={
            configDialog.useSelectedScope === false
              ? null
              : selectedExecutionScope
          }
          onSuccess={async () => {
            setConfigDialog(null);
            // Refetch tools to get updated status
            await refetchTools();
          }}
        />
      )}
    </>
  );
}
