// [nexus] Provider selection step — Step 3 of 4 in the onboarding wizard
// Heading: "Choose a provider" / Subheading: "No API keys needed for the zero-config path."
// Three provider cards (Puter, Google, API key) with adapter badges and skip button
import { useState } from "react";
import { cn } from "@/lib/utils";
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;
  onSkip: () => void;
  onContinue: () => void;
  detectedAdapters: Record<string, boolean>;
}

type ProviderChoice = "puter" | "google" | "apikey" | null;

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

  function handleSelect(provider: ProviderChoice) {
    setSelectedProvider(provider);
    setProviderReady(false);
    setError(null);
  }

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

  return (
    <div className="flex flex-col gap-4">
      {/* Three provider cards */}
      <div className="flex flex-col gap-3">
        {/* Puter card */}
        <button
          type="button"
          onClick={() => handleSelect("puter")}
          className={cn(
            "flex flex-col gap-1 rounded-lg border p-4 text-left transition-colors",
            selectedProvider === "puter"
              ? "border-primary bg-primary/5"
              : "border-border hover:border-muted-foreground/50"
          )}
        >
          <div className="flex items-center gap-2 flex-wrap">
            <span className="font-medium text-sm">Puter -- free, zero-config</span>
            {hermesDetected && (
              <span className="text-xs text-primary">Hermes detected</span>
            )}
            {claudeDetected && (
              <span className="text-xs text-primary">Claude Code detected</span>
            )}
            {openclawDetected && (
              <span className="text-xs text-primary">OpenClaw detected</span>
            )}
          </div>
          <span className="text-xs text-muted-foreground">
            Free AI powered by your Puter.com account. No API key needed.
          </span>
        </button>

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

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

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

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

        {/* API key form — shown when API key is selected */}
        {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>
      )}

      {/* Continue button — shown when provider auth is complete */}
      {providerReady && (
        <Button type="button" onClick={onContinue} className="w-full">
          Continue
        </Button>
      )}

      {/* Skip button — always visible */}
      <Button
        type="button"
        variant="ghost"
        onClick={onSkip}
        aria-label="Skip provider setup for now"
        className="w-full"
      >
        Skip for now
      </Button>
    </div>
  );
}
