import { ChangeDetectionStrategy, Component, ElementRef, EventEmitter, Output, ViewChild } from '@angular/core';
import { MatIconModule } from '@angular/material/icon';
import { MatButtonModule } from '@angular/material/button';

/**
 * Global Action Modal — overlay for fleet-wide commands.
 *
 * Four main actions: Deploy All, Pause All, Emergency Stop, Add Agent.
 * Tactical Dark Mode styling using Control Center design tokens.
 * Dismisses on backdrop click or close button.
 */
@Component({
  selector: 'app-global-action-modal',
  standalone: true,
  imports: [MatIconModule, MatButtonModule],
  templateUrl: './global-action-modal.component.html',
  styleUrl: './global-action-modal.component.scss',
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class GlobalActionModalComponent {
  /** Emitted when any action button is clicked. Payload is the action key. */
  @Output() readonly actionSelected = new EventEmitter<GlobalAction>();

  /** Emitted when the modal is dismissed (backdrop click or close button). */
  @Output() readonly dismissed = new EventEmitter<void>();

  @ViewChild('backdrop') backdropEl!: ElementRef<HTMLElement>;

  /** All available global actions. */
  readonly actions: GlobalActionDef[] = [
    {
      key: 'deploy-all',
      label: 'Deploy All',
      description: 'Deploy all agents in the fleet',
      icon: 'rocket_launch',
      color: 'deploy',
    },
    {
      key: 'pause-all',
      label: 'Pause All',
      description: 'Pause all running agents',
      icon: 'pause_circle',
      color: 'pause',
    },
    {
      key: 'emergency-stop',
      label: 'Emergency Stop',
      description: 'Immediately halt all agents',
      icon: 'emergency',
      color: 'emergency',
    },
    {
      key: 'add-agent',
      label: 'Add Agent',
      description: 'Register a new agent to the fleet',
      icon: 'person_add',
      color: 'add',
    },
  ];

  onBackdropClick(): void {
    this.dismissed.emit();
  }

  onModalClick(event: Event): void {
    // Prevent clicks inside the modal panel from closing it
    event.stopPropagation();
  }

  onClose(): void {
    this.dismissed.emit();
  }

  onAction(action: GlobalActionDef): void {
    this.actionSelected.emit(action.key);
  }
}

export type GlobalAction = 'deploy-all' | 'pause-all' | 'emergency-stop' | 'add-agent';

export interface GlobalActionDef {
  key: GlobalAction;
  label: string;
  description: string;
  icon: string;
  color: 'deploy' | 'pause' | 'emergency' | 'add';
}