'use client';

import * as React from 'react';
import ScopePicker from './scope-picker.jsx';

/**
 * API-key setup step. Renders one password / text input per credential
 * declared in the connection manifest, plus a scope picker at the top
 * (global / project / agent). Never re-displays a saved secret — the
 * field starts empty even for a connected service (entering a new
 * value rotates the key at the chosen scope).
 *
 * @param {{
 *   connection: any,
 *   credentials: Record<string, string>,
 *   onChange: (next: Record<string, string>) => void,
 *   scope: { scope: string, project_id: string|null, agent_id: string|null },
 *   onScopeChange: (next) => void,
 *   onSubmit: (credentials: Record<string, string>) => void,
 *   onCancel: () => void,
 *   error?: string|null,
 *   hint?: string|null,
 *   busy?: boolean,
 * }} props
 */
export default function ApiKeyStep({
  connection,
  credentials,
  onChange,
  scope,
  onScopeChange,
  onSubmit,
  onCancel,
  error,
  hint,
  busy,
}) {
  const fields = connection?.connection?.credentials || connection?.manifest?.credentials || [];
  const supportsScopes = Array.isArray(connection?.connection?.supports_scopes)
    ? connection.connection.supports_scopes
    : (Array.isArray(connection?.manifest?.supports_scopes)
        ? connection.manifest.supports_scopes
        : ['global', 'project', 'agent']);

  function handleSubmit(event) {
    event.preventDefault();
    onSubmit(credentials);
  }

  function setField(name, value) {
    onChange({ ...credentials, [name]: value });
  }

  const allRequiredPresent = fields
    .filter(f => f.required)
    .every(f => String(credentials[f.name] || '').trim().length > 0);

  const scopeReady = scope.scope === 'global'
    || (scope.scope === 'project' && Boolean(scope.project_id))
    || (scope.scope === 'agent' && Boolean(scope.agent_id));

  return (
    <form className="connection-setup-step connection-setup-step-form" onSubmit={handleSubmit}>
      <p className="connection-setup-intro">
        Madarx will use this to {connection.connection?.benefit || 'connect to the service'}.{' '}
        Your credentials are encrypted on this Mac and never echoed back.
      </p>

      <ScopePicker
        value={scope}
        onChange={onScopeChange}
        supportsScopes={supportsScopes}
        disabled={busy}
      />

      {fields.map(field => (
        <label key={field.name} className="connection-setup-field">
          <span className="connection-setup-field-label">
            {field.label}
            {field.required ? null : <small> (optional)</small>}
          </span>
          <input
            type={field.type === 'password' ? 'password' : 'text'}
            name={field.name}
            placeholder={field.placeholder || ''}
            autoComplete="off"
            spellCheck={false}
            value={credentials[field.name] || ''}
            onChange={e => setField(field.name, e.target.value)}
            disabled={busy}
          />
          {field.help_text || field.help_url ? (
            <small className="connection-setup-field-help">
              {field.help_text || 'Find this in the provider settings.'}
              {field.help_url ? (
                <>
                  {' '}
                  <a href={field.help_url} target="_blank" rel="noreferrer noopener">Where do I find this? →</a>
                </>
              ) : null}
            </small>
          ) : null}
        </label>
      ))}

      {error ? (
        <p className="connection-setup-error">
          {error}
          {hint ? <small> {hint}</small> : null}
        </p>
      ) : null}

      <div className="connection-setup-actions">
        <button
          type="button"
          className="admin-button secondary"
          onClick={onCancel}
          disabled={busy}
        >
          Cancel
        </button>
        <button
          type="submit"
          className="admin-button"
          disabled={busy || !allRequiredPresent || !scopeReady}
        >
          {busy ? 'Verifying…' : 'Connect'}
        </button>
      </div>
    </form>
  );
}
