// [nexus] API key entry form — provider dropdown + secret key input
import { useState } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { CheckCircle } from "lucide-react";

interface ApiKeyEntryFormProps {
  onSave: (provider: string, apiKey: string) => void;
  onError: (msg: string) => void;
}

const PROVIDERS = [
  { value: "openai", label: "OpenAI" },
  { value: "anthropic", label: "Anthropic" },
  { value: "groq", label: "Groq" },
];

export function ApiKeyEntryForm({ onSave, onError }: ApiKeyEntryFormProps) {
  const [provider, setProvider] = useState("openai");
  const [apiKey, setApiKey] = useState("");
  const [saved, setSaved] = useState(false);

  function handleSave() {
    if (!apiKey.trim()) {
      onError("Could not save API key. Check the key is valid and try again.");
      return;
    }
    onSave(provider, apiKey.trim());
    setSaved(true);
  }

  return (
    <div className="flex flex-col gap-3">
      <div className="flex flex-col gap-2">
        <Label htmlFor="api-key-provider">Provider</Label>
        <select
          id="api-key-provider"
          value={provider}
          onChange={(e) => setProvider(e.target.value)}
          disabled={saved}
          className="flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors focus:outline-none focus:ring-1 focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50"
        >
          {PROVIDERS.map((p) => (
            <option key={p.value} value={p.value}>
              {p.label}
            </option>
          ))}
        </select>
      </div>

      <div className="flex flex-col gap-2">
        <Label htmlFor="api-key-value">API key</Label>
        <Input
          id="api-key-value"
          type="password"
          placeholder="sk-..."
          value={apiKey}
          onChange={(e) => setApiKey(e.target.value)}
          disabled={saved}
          autoComplete="off"
          className="font-mono text-sm"
        />
      </div>

      <Button
        type="button"
        onClick={handleSave}
        disabled={saved || !apiKey.trim()}
        className="w-full"
      >
        {saved ? (
          <span className="flex items-center gap-2">
            <CheckCircle className="h-4 w-4" />
            API key saved
          </span>
        ) : (
          "Save API key"
        )}
      </Button>
    </div>
  );
}
