'use client';

import * as React from 'react';

/**
 * Hermes detection step. Calls the verify endpoint up-front (with no overrides)
 * to find out whether the default path resolves. If it does, the user can just
 * confirm. If not, they can paste an override path and re-verify.
 */
export default function BinaryDetectStep({ connection, credentials, onChange, onSubmit, onCancel, busy }) {
  const verifyEndpoint = connection?.connection?.verify_endpoint;
  const [probe, setProbe] = React.useState(null);
  const [probeError, setProbeError] = React.useState(null);
  const [probing, setProbing] = React.useState(false);

  const probeOnce = React.useCallback(async () => {
    if (!verifyEndpoint) return;
    setProbing(true);
    setProbeError(null);
    try {
      const res = await fetch(verifyEndpoint, {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({ credentials: {}, dry_run: true }),
      });
      const data = await res.json().catch(() => ({}));
      setProbe(data);
    } catch {
      setProbeError("We couldn't probe the local Hermes path.");
    } finally {
      setProbing(false);
    }
  }, [verifyEndpoint]);

  React.useEffect(() => {
    probeOnce();
  }, [probeOnce]);

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

  const overrideField = (connection?.connection?.credentials || []).find(f => f.name === 'HERMES_AGENT_DIR');
  const detectedPath = probe?.probe?.hermes_dir
    || probe?.connection?.connection?.summary?.hermes_dir
    || probe?.hermes_dir
    || probe?.connection?.connection?.account_label;
  const detectedOk = probe?.ok === true;

  return (
    <form className="connection-setup-step connection-setup-step-form" onSubmit={handleSubmit}>
      <p className="connection-setup-intro">
        Madarx looks for a local Hermes checkout at <code>../hermes-agent</code>. Override the path
        below if your checkout lives elsewhere.
      </p>

      <div className={`connection-setup-probe ${detectedOk ? 'ok' : 'warn'}`}>
        {probing ? (
          <span>Probing…</span>
        ) : detectedOk ? (
          <span>
            <b>Hermes detected.</b> Path: <code>{detectedPath}</code>
          </span>
        ) : (
          <span>
            <b>Hermes not detected.</b> {probe?.hint || probeError || 'Provide an override path or clone hermes-agent.'}
          </span>
        )}
      </div>

      {overrideField ? (
        <label className="connection-setup-field">
          <span className="connection-setup-field-label">
            {overrideField.label}
          </span>
          <input
            type="text"
            name={overrideField.name}
            placeholder={overrideField.placeholder || ''}
            autoComplete="off"
            spellCheck={false}
            value={credentials[overrideField.name] || ''}
            onChange={e => onChange({ ...credentials, [overrideField.name]: e.target.value })}
            disabled={busy}
          />
          <small className="connection-setup-field-help">
            {overrideField.help_text}
          </small>
        </label>
      ) : null}

      <div className="connection-setup-actions">
        <button
          type="button"
          className="admin-button secondary"
          onClick={onCancel}
          disabled={busy}
        >
          Cancel
        </button>
        <button
          type="button"
          className="admin-button secondary"
          onClick={probeOnce}
          disabled={busy || probing}
        >
          {probing ? 'Probing…' : 'Re-detect'}
        </button>
        <button
          type="submit"
          className="admin-button"
          disabled={busy || (!detectedOk && !credentials[overrideField?.name])}
        >
          {busy ? 'Verifying…' : 'Connect'}
        </button>
      </div>
    </form>
  );
}
