import { ChangeDetectionStrategy, Component, Input, OnDestroy, signal, computed } from '@angular/core';
import { CommonModule } from '@angular/common';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { MatChipsModule } from '@angular/material/chips';
import { MatTooltipModule } from '@angular/material/tooltip';
import { AgentSummary, SystemHealth } from '../../models/agent.model';

@Component({
  selector: 'app-dashboard-summary',
  standalone: true,
  imports: [
    CommonModule,
    MatButtonModule,
    MatIconModule,
    MatChipsModule,
    MatTooltipModule,
  ],
  templateUrl: './dashboard-summary.component.html',
  styleUrls: ['./dashboard-summary.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class DashboardSummaryComponent implements OnDestroy {
  /** Agent summary data — reactive signal, updatable via updateSummary() */
  readonly summary = signal<AgentSummary>({
    total: 0,
    active: 0,
    idle: 0,
    thinking: 0,
    error: 0,
  });

  /** System health data — reactive signal, updatable via updateHealth() */
  readonly health = signal<SystemHealth>({
    connected: false,
    status: 'down',
  });

  /** Computed signal: whether there are errors to highlight */
  readonly hasErrors = computed(() => this.summary().error > 0);

  /** Computed signal: whether system is degraded */
  readonly isDegraded = computed(() => this.health().status === 'degraded');

  /** Computed signal: whether system is down */
  readonly isDown = computed(() => this.health().status === 'down');

  /** Computed signal: connection indicator color */
  readonly connectionColor = computed(() =>
    this.health().connected ? 'connected' : 'disconnected'
  );

  /** Computed signal: overall status label */
  readonly statusLabel = computed(() => {
    const h = this.health();
    if (h.status === 'healthy') return 'All Systems Go';
    if (h.status === 'degraded') return 'Degraded';
    return 'Offline';
  });

  /**
   * Update the agent summary. Called by the parent or a service
   * when new data arrives (e.g., via SignalR).
   */
  updateSummary(data: AgentSummary): void {
    this.summary.set(data);
  }

  /**
   * Update the system health. Called by the parent or a service
   * when the connection state changes.
   */
  updateHealth(data: SystemHealth): void {
    this.health.set(data);
  }

  ngOnDestroy(): void {
    // Cleanup handled by signals — no manual subscription teardown needed
  }
}