import { CommonModule } from '@angular/common';
import { Component, Input, inject } from '@angular/core';

import { CutoverI18nService } from '../core/cutover-i18n.service';

type LiveRecord = Record<string, unknown>;

type SummaryMetric = {
  label: string;
  value: string;
};

type LivePanel = {
  title: string;
  description: string;
  data: unknown;
  metrics: SummaryMetric[];
  previewRows: LiveRecord[];
  previewKeys: string[];
  narrative: string;
};

@Component({
  selector: 'app-journey-live-surface',
  standalone: true,
  imports: [CommonModule],
  template: `
    <section class="data-surface-panel" *ngIf="metrics.length || toolbarPills.length">
      <div class="stage-summary-grid compact">
        <article class="summary-card" *ngFor="let metric of metrics">
          <span class="meta-label">{{ t(metric.label) }}</span>
          <strong>{{ t(metric.value) }}</strong>
        </article>
      </div>
      <div class="report-toolbar-strip">
        <span class="toolbar-pill" *ngFor="let pill of toolbarPills">{{ t(pill) }}</span>
      </div>
    </section>

      <div class="panel-stack" *ngIf="panels.length; else noPanels">
      <section class="live-panel" *ngFor="let panel of panels">
        <div class="live-panel__head">
          <div>
            <strong>{{ t(panel.title) }}</strong>
          </div>
          <span class="state-badge">{{ panel.previewRows.length ? t('Rows') + ': ' + panel.previewRows.length : t('Metrics') + ': ' + panel.metrics.length }}</span>
        </div>
        <div class="panel-summary-row" *ngIf="panel.metrics.length">
          <span class="panel-summary-chip" *ngFor="let metric of panel.metrics">
            <strong>{{ t(metric.label) }}:</strong> {{ t(metric.value) }}
          </span>
        </div>
        <div class="preview-table-shell" *ngIf="panel.previewRows.length">
          <table class="preview-table">
            <thead>
              <tr>
                <th *ngFor="let key of panel.previewKeys">{{ prettifyKey(key) }}</th>
              </tr>
            </thead>
            <tbody>
              <tr *ngFor="let row of panel.previewRows">
                <td *ngFor="let key of panel.previewKeys">{{ formatPreviewValue(row[key]) }}</td>
              </tr>
            </tbody>
          </table>
        </div>
      </section>
    </div>
    <ng-template #noPanels></ng-template>
  `
})
export class JourneyLiveSurfaceComponent {
  private readonly i18n = inject(CutoverI18nService);

  @Input() title = '';
  @Input() summary = '';
  @Input() toolbarPills: readonly string[] = [];
  @Input() metrics: readonly SummaryMetric[] = [];
  @Input() panels: readonly LivePanel[] = [];

  protected t(value: string): string {
    return this.i18n.text(value);
  }

  protected prettifyKey(key: string): string {
    return this.t(this.prettifyLabel(key));
  }

  protected formatPreviewValue(value: unknown): string {
    if (value == null) {
      return '-';
    }

    if (Array.isArray(value)) {
      return this.t(`${value.length} items`);
    }

    if (typeof value === 'object') {
      return this.t('Object');
    }

    if (typeof value === 'boolean') {
      return this.t(value ? 'Yes' : 'No');
    }

    if (typeof value === 'string') {
      const exactTranslation = this.t(value);
      if (exactTranslation !== value) {
        return exactTranslation;
      }

      if (/[A-Z_]/.test(value) || /[a-z][A-Z]/.test(value)) {
        const pretty = this.prettifyLabel(value);
        const prettyTranslation = this.t(pretty);
        if (prettyTranslation !== pretty) {
          return prettyTranslation;
        }
      }
    }

    return String(value);
  }

  private prettifyLabel(key: string): string {
    return key
      .replace(/([a-z0-9])([A-Z])/g, '$1 $2')
      .replace(/_/g, ' ')
      .replace(/\b\w/g, (char) => char.toUpperCase());
  }
}
