// [nexus] Provider selection step — Step 3 of 6 in the onboarding wizard
// Separated detected adapters section from provider cards
import { useState } from "react";
import { cn } from "@/lib/utils";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { PuterAuthButton } from "./PuterAuthButton";
import { GoogleOAuthButton } from "./GoogleOAuthButton";
import { ApiKeyEntryForm } from "./ApiKeyEntryForm";

interface ProviderSelectionStepProps {
  onPuterToken: (token: string) => void;
  onGoogleOAuthState: (stateId: string) => void;
  onApiKey: (provider: string, apiKey: string) => void;
  onAdapterSelected: (adapter: string | null) => void;
  onSkip: () => void;
  onContinue: () => void;
  detectedAdapters: Record<string, boolean>;
  probing?: boolean;
}

type ProviderChoice = "puter" | "google" | "apikey" | null;
type AdapterChoice = "claude_local" | "hermes_local" | "openclaw_gateway" | null;

const ADAPTER_INFO: Record<string, { name: string; description: string }> = {
  claude_local: { name: "Claude Code", description: "CLI agent — uses your Anthropic API key" },
  hermes_local: { name: "Hermes", description: "Free local agent — no API key needed" },
  openclaw_gateway: { name: "OpenClaw Gateway", description: "Multi-model gateway" },
};

export function ProviderSelectionStep({
  onPuterToken,
  onGoogleOAuthState,
  onApiKey,
  onAdapterSelected,
  onSkip,
  onContinue,
  detectedAdapters,
  probing,
}: ProviderSelectionStepProps) {
  const [selectedProvider, setSelectedProvider] = useState<ProviderChoice>(null);
  const [selectedAdapter, setSelectedAdapter] = useState<AdapterChoice>(null);
  const [providerReady, setProviderReady] = useState(false);
  const [error, setError] = useState<string | null>(null);

  function handleSelectProvider(provider: ProviderChoice) {
    setSelectedProvider(provider);
    setSelectedAdapter(null);
    setProviderReady(false);
    setError(null);
    onAdapterSelected(null);
  }

  function handleSelectAdapter(adapter: AdapterChoice) {
    setSelectedAdapter(adapter);
    setSelectedProvider(null);
    setProviderReady(false);
    setError(null);
    onAdapterSelected(adapter);
  }

  const hermesDetected = detectedAdapters["hermes_local"] === true;
  const claudeDetected = detectedAdapters["claude_local"] === true;
  const openclawDetected = detectedAdapters["openclaw_gateway"] === true;
  const hasDetectedAdapters = hermesDetected || claudeDetected || openclawDetected;

  // Determine if continue should be active
  const canContinue = selectedAdapter !== null || (selectedProvider !== null && providerReady);
  const hasSelection = selectedAdapter !== null || selectedProvider !== null;

  function handleContinue() {
    if (selectedAdapter) {
      onContinue();
    } else if (selectedProvider && providerReady) {
      onContinue();
    }
  }

  return (
    <div className="flex flex-col gap-6">
      {/* Detected local adapters section */}
      {(probing || hasDetectedAdapters) && (
        <div className="flex flex-col gap-3">
          <p className="text-sm font-medium text-muted-foreground">Detected on this machine</p>
          {probing ? (
            <div className="flex items-center gap-3 rounded-lg border border-border p-4">
              <svg className="h-4 w-4 animate-spin text-muted-foreground" viewBox="0 0 24 24" fill="none">
                <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
                <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
              </svg>
              <span className="text-sm text-muted-foreground">Checking for installed tools...</span>
            </div>
          ) : (
            <div className="flex flex-col gap-2">
              {(["claude_local", "hermes_local", "openclaw_gateway"] as const).map((key) => {
                if (!detectedAdapters[key]) return null;
                const info = ADAPTER_INFO[key];
                const isSelected = selectedAdapter === key;
                return (
                  <button
                    key={key}
                    type="button"
                    onClick={() => handleSelectAdapter(key)}
                    className={cn(
                      "flex items-center justify-between rounded-lg border p-4 text-left transition-colors w-full",
                      isSelected
                        ? "border-l-2 border-l-primary bg-primary/5"
                        : "border-border hover:border-muted-foreground/50"
                    )}
                  >
                    <div className="flex flex-col gap-0.5">
                      <span className="text-sm font-medium">{info.name}</span>
                      <span className="text-xs text-muted-foreground">{info.description}</span>
                    </div>
                    <Badge variant="outline" className="text-[color:var(--chart-2)] border-[color:var(--chart-2)]/30 bg-[color:var(--chart-2)]/10 shrink-0 ml-3">
                      Detected
                    </Badge>
                  </button>
                );
              })}
            </div>
          )}
        </div>
      )}

      {/* Cloud provider cards */}
      <div className="flex flex-col gap-3">
        <p className="text-sm font-medium text-muted-foreground">Cloud providers</p>

        {/* Puter card */}
        <button
          type="button"
          onClick={() => handleSelectProvider("puter")}
          className={cn(
            "flex flex-col gap-1 rounded-lg border p-4 text-left transition-colors w-full",
            selectedProvider === "puter"
              ? "border-l-2 border-l-[var(--primary)] bg-[var(--primary)]/5"
              : "border-border hover:border-muted-foreground/50"
          )}
        >
          <span className="text-base font-medium">Puter -- free, zero-config</span>
          <span className="text-sm text-muted-foreground">
            Free AI powered by your Puter.com account. No API key needed.
          </span>
        </button>

        {/* Puter auth component */}
        {selectedProvider === "puter" && (
          <PuterAuthButton
            onSuccess={(token) => {
              onPuterToken(token);
              setProviderReady(true);
            }}
            onError={setError}
          />
        )}

        {/* Google card */}
        <button
          type="button"
          onClick={() => handleSelectProvider("google")}
          className={cn(
            "flex flex-col gap-1 rounded-lg border p-4 text-left transition-colors w-full",
            selectedProvider === "google"
              ? "border-l-2 border-l-[var(--primary)] bg-[var(--primary)]/5"
              : "border-border hover:border-muted-foreground/50"
          )}
        >
          <span className="text-base font-medium">Google Gemini -- free tier</span>
          <span className="text-sm text-muted-foreground">
            Sign in with Google to access Gemini via your Google account.
          </span>
        </button>

        {/* Google OAuth component */}
        {selectedProvider === "google" && (
          <GoogleOAuthButton
            onSuccess={(stateId) => {
              onGoogleOAuthState(stateId);
              setProviderReady(true);
            }}
            onError={setError}
          />
        )}

        {/* API key card */}
        <button
          type="button"
          onClick={() => handleSelectProvider("apikey")}
          className={cn(
            "flex flex-col gap-1 rounded-lg border p-4 text-left transition-colors w-full",
            selectedProvider === "apikey"
              ? "border-l-2 border-l-[var(--primary)] bg-[var(--primary)]/5"
              : "border-border hover:border-muted-foreground/50"
          )}
        >
          <span className="text-base font-medium">API key -- subscription provider</span>
          <span className="text-sm text-muted-foreground">
            Use your own OpenAI, Anthropic, or Groq API key.
          </span>
        </button>

        {/* API key form */}
        {selectedProvider === "apikey" && (
          <ApiKeyEntryForm
            onSave={(prov, key) => {
              onApiKey(prov, key);
              setProviderReady(true);
            }}
            onError={setError}
          />
        )}
      </div>

      {/* Error display */}
      {error && (
        <p className="text-sm text-destructive bg-destructive/10 rounded-md px-3 py-2">
          {error}
        </p>
      )}

      {/* Single bottom action — contextual based on selection state */}
      <div className="flex items-center justify-center mt-2">
        {canContinue ? (
          <Button type="button" onClick={handleContinue} className="w-full">
            Continue
          </Button>
        ) : (
          <button
            type="button"
            className="text-sm text-muted-foreground hover:text-foreground transition-colors"
            onClick={onSkip}
          >
            Continue without a provider
          </button>
        )}
      </div>
    </div>
  );
}
