import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';

export interface HeaderAction {
  id: string;
  label: string;
  icon: string;
  type: 'primary' | 'secondary';
  action: () => void;
  visible: boolean;
  disabled?: boolean;
  tooltip?: string;
}

export interface HeaderConfig {
  domain: string;
  title?: string;
  actions: HeaderAction[];
  recordCount?: number;
}

@Injectable({
  providedIn: 'root'
})
export class HeaderActionsService {
  private configSubject = new BehaviorSubject<HeaderConfig>({
    domain: '',
    actions: []
  });
  
  public config$ = this.configSubject.asObservable();

  constructor() {}

  /**
   * Define a configuração do header para um domínio específico
   */
  setDomainConfig(config: HeaderConfig): void {
    this.configSubject.next(config);
  }

  /**
   * Limpa a configuração do header
   */
  clearConfig(): void {
    this.configSubject.next({
      domain: '',
      actions: []
    });
  }

  /**
   * Atualiza uma ação específica
   */
  updateAction(actionId: string, updates: Partial<HeaderAction>): void {
    const currentConfig = this.configSubject.value;
    const actionIndex = currentConfig.actions.findIndex(action => action.id === actionId);
    
    if (actionIndex !== -1) {
      const updatedActions = [...currentConfig.actions];
      updatedActions[actionIndex] = { ...updatedActions[actionIndex], ...updates };
      
      this.configSubject.next({
        ...currentConfig,
        actions: updatedActions
      });
    }
  }

  /**
   * Adiciona uma nova ação
   */
  addAction(action: HeaderAction): void {
    const currentConfig = this.configSubject.value;
    this.configSubject.next({
      ...currentConfig,
      actions: [...currentConfig.actions, action]
    });
  }

  /**
   * Remove uma ação
   */
  removeAction(actionId: string): void {
    const currentConfig = this.configSubject.value;
    this.configSubject.next({
      ...currentConfig,
      actions: currentConfig.actions.filter(action => action.id !== actionId)
    });
  }

  /**
   * Executa uma ação por ID
   */
  executeAction(actionId: string): void {
    const currentConfig = this.configSubject.value;
    const action = currentConfig.actions.find(a => a.id === actionId);
    
    if (action && action.visible && !action.disabled) {
      action.action();
    }
  }

  /**
   * Atualiza o contador de registros do domain atual
   */
  updateRecordCount(count: number): void {
    const currentConfig = this.configSubject.value;
    this.configSubject.next({
      ...currentConfig,
      recordCount: count
    });
  }
} 