// src/flow/viewers/CommandResultViewer.ts
//
// CommandResultViewer - Displays command execution results.

import { MatrixActorHtmlElement } from '../../framework/MatrixActorHtmlElement';
import { ShellRegistry } from '../ShellRegistry';

/**
 * CommandResultViewer - Displays command execution results.
 *
 * Accepts:
 *   - setResult: { command, params, response, durationMs, targetMount, success }
 *   - retry: {}
 *   - copyResult: {}
 *
 * Emits:
 *   - retried: {}
 *   - copied: {}
 */
export class CommandResultViewer extends MatrixActorHtmlElement {
  static accepts = {
    setResult: {
      command: 'string',
      params: 'any?',
      response: 'any?',
      durationMs: 'number?',
      targetMount: 'string?',
      success: 'boolean?',
    },
    retry: {},
    copyResult: {},
  };

  static emits = {
    retried: {},
    copied: {},
  };

  static template = `
    <div class="command-result-viewer">
      <div id="header" class="result-header">
        <span id="statusIcon" class="status-icon"></span>
        <span id="command" class="command-name"></span>
        <span id="duration" class="duration"></span>
        <div class="actions">
          <button id="retryBtn" title="Retry command">Retry</button>
          <button id="copyBtn" title="Copy result">Copy</button>
        </div>
      </div>
      <div class="result-body">
        <div id="targetSection" class="section target-section" style="display:none">
          <span class="section-label">Target:</span>
          <code id="targetMount" class="mount-path"></code>
        </div>
        <div id="paramsSection" class="section params-section" style="display:none">
          <span class="section-label">Params:</span>
          <pre id="params" class="params-content"></pre>
        </div>
        <div class="section response-section">
          <span class="section-label">Response:</span>
          <pre id="response" class="response-content"></pre>
        </div>
      </div>
    </div>
    <style>
      :host { display: block; }
      .command-result-viewer {
        border: 1px solid var(--mx-color-border-light, #e0e0e0);
        border-radius: 8px;
        background: var(--mx-color-surface-alt, #fafafa);
        overflow: hidden;
      }
      .result-header {
        padding: 10px 12px;
        background: var(--mx-color-surface-hover, #e8f5e9);
        border-bottom: 1px solid var(--mx-color-border, #c8e6c9);
        display: flex;
        align-items: center;
        gap: 10px;
      }
      .result-header.error {
        background: var(--mx-color-surface-hover, #ffebee);
        border-bottom-color: var(--mx-color-error, #ffcdd2);
      }
      .status-icon {
        width: 18px;
        height: 18px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 12px;
        font-weight: bold;
      }
      .status-icon.success {
        background: var(--mx-color-success, #4caf50);
        color: white;
      }
      .status-icon.error {
        background: var(--mx-color-error, #f44336);
        color: white;
      }
      .command-name {
        font-family: monospace;
        font-weight: 600;
        color: var(--mx-color-text, #333);
        font-size: 14px;
      }
      .duration {
        font-size: 11px;
        color: var(--mx-color-text-secondary, #666);
        background: rgba(0,0,0,0.05);
        padding: 2px 8px;
        border-radius: 10px;
      }
      .actions {
        margin-left: auto;
        display: flex;
        gap: 4px;
      }
      .actions button {
        padding: 4px 10px;
        border: 1px solid var(--mx-color-border, #ccc);
        border-radius: 4px;
        background: var(--mx-color-surface, white);
        cursor: pointer;
        font-size: 11px;
      }
      .actions button:hover {
        background: var(--mx-color-surface-hover, #e3f2fd);
        border-color: var(--mx-color-primary, #1976d2);
      }
      .result-body {
        padding: 12px;
      }
      .section {
        margin-bottom: 12px;
      }
      .section:last-child {
        margin-bottom: 0;
      }
      .section-label {
        display: block;
        font-size: 11px;
        font-weight: 600;
        color: var(--mx-color-text-secondary, #666);
        text-transform: uppercase;
        margin-bottom: 4px;
      }
      .mount-path {
        font-family: monospace;
        font-size: 12px;
        background: var(--mx-color-surface-hover, #e3f2fd);
        padding: 4px 8px;
        border-radius: 4px;
        color: var(--mx-color-link, #1565c0);
      }
      .params-content, .response-content {
        font-family: 'Consolas', 'Monaco', monospace;
        font-size: 12px;
        background: var(--mx-color-surface, white);
        padding: 10px;
        border-radius: 4px;
        border: 1px solid var(--mx-color-border-light, #e0e0e0);
        overflow: auto;
        max-height: 200px;
        white-space: pre-wrap;
        word-break: break-word;
        margin: 0;
      }
    </style>
  `;

  private _result: {
    command: string;
    params?: unknown;
    response?: unknown;
    durationMs?: number;
    targetMount?: string;
    success?: boolean;
  } | null = null;

  get result() {
    return this._result;
  }

  async onBootstrap(): Promise<void> {

    // Initialize from props if passed
    // Note: _initialProps is dynamically set by parent during child creation
    const props = (this as unknown as { _initialProps?: { data?: Record<string, unknown>; label?: string } })._initialProps;
    if (props?.data !== undefined) {
      this.onSetResult({
        command: String(props.data.command || props.label || 'command'),
        params: props.data.params,
        response: props.data.response,
        durationMs: typeof props.data.durationMs === 'number' ? props.data.durationMs : undefined,
        targetMount: typeof props.data.targetMount === 'string' ? props.data.targetMount : undefined,
        success: typeof props.data.success === 'boolean' ? props.data.success : undefined,
      });
    }

    // Wire up button handlers
    const retryBtn = this.shadowRoot?.getElementById('retryBtn');
    const copyBtn = this.shadowRoot?.getElementById('copyBtn');

    retryBtn?.addEventListener('click', () => this.onRetry());
    copyBtn?.addEventListener('click', () => {
      navigator.clipboard?.writeText(this.getFormattedResponse());
      this.onCopyResult();
    });

    // Initial render
    this.render();
  }

  onSetResult(params: {
    command: string;
    params?: unknown;
    response?: unknown;
    durationMs?: number;
    targetMount?: string;
    success?: boolean;
  }): void {
    this._result = params;
    this.render();
  }

  onRetry(): void {
    this.emit('retried', {});
  }

  onCopyResult(): void {
    this.emit('copied', {});
  }

  getFormattedParams(): string {
    if (!this._result?.params) return '';
    try {
      return JSON.stringify(this._result.params, null, 2);
    } catch {
      return String(this._result.params);
    }
  }

  getFormattedResponse(): string {
    if (this._result?.response === undefined) return 'void';
    try {
      return JSON.stringify(this._result.response, null, 2);
    } catch {
      return String(this._result.response);
    }
  }

  /**
   * Render the component's DOM.
   */
  render(): void {
    const headerEl = this.shadowRoot?.getElementById('header');
    const statusIconEl = this.shadowRoot?.getElementById('statusIcon');
    const commandEl = this.shadowRoot?.getElementById('command');
    const durationEl = this.shadowRoot?.getElementById('duration');
    const targetSectionEl = this.shadowRoot?.getElementById('targetSection');
    const targetMountEl = this.shadowRoot?.getElementById('targetMount');
    const paramsSectionEl = this.shadowRoot?.getElementById('paramsSection');
    const paramsEl = this.shadowRoot?.getElementById('params');
    const responseEl = this.shadowRoot?.getElementById('response');

    const result = this._result;
    if (!result) return;

    const isSuccess = result.success !== false;

    // Header styling
    if (headerEl) {
      headerEl.classList.toggle('error', !isSuccess);
    }

    // Status icon
    if (statusIconEl) {
      statusIconEl.textContent = isSuccess ? '✓' : '✗';
      statusIconEl.className = `status-icon ${isSuccess ? 'success' : 'error'}`;
    }

    // Command name
    if (commandEl) {
      commandEl.textContent = result.command || '';
    }

    // Duration
    if (durationEl) {
      durationEl.textContent = result.durationMs !== undefined ? `${result.durationMs}ms` : '';
      durationEl.style.display = result.durationMs !== undefined ? 'inline' : 'none';
    }

    // Target mount
    if (targetSectionEl && targetMountEl) {
      if (result.targetMount) {
        targetSectionEl.style.display = 'block';
        targetMountEl.textContent = result.targetMount;
      } else {
        targetSectionEl.style.display = 'none';
      }
    }

    // Params
    if (paramsSectionEl && paramsEl) {
      const formattedParams = this.getFormattedParams();
      if (formattedParams) {
        paramsSectionEl.style.display = 'block';
        paramsEl.textContent = formattedParams;
      } else {
        paramsSectionEl.style.display = 'none';
      }
    }

    // Response
    if (responseEl) {
      responseEl.textContent = this.getFormattedResponse();
    }
  }
}

// Keep CommandResultViewerShell as alias for backwards compatibility
export const CommandResultViewerShell = CommandResultViewer;

// Register with ShellRegistry
ShellRegistry.register('CommandResultViewer', {
  shellTag: 'command-result-viewer',
  moduleUrl: import.meta.url,
});

// Register custom element
if (typeof customElements !== 'undefined' && !customElements.get('command-result-viewer')) {
  customElements.define('command-result-viewer', CommandResultViewer);
}
