import { ChangeDetectionStrategy, Component, inject, signal } from '@angular/core';
import { CommonModule } from '@angular/common';
import { AdminPartnerHierarchyFacade } from '../facade/admin-partner-hierarchy.facade';
import { BadgeComponent } from '../../../../shared/ui/badge/badge.component';
import { ConfirmDialogComponent } from '../../../../shared/ui/confirm-dialog/confirm-dialog.component';
import { Environment, NodeStatus, ProvisioningNode } from '../../../../core/partner-hierarchy/models/provisioning-node.model';

@Component({
  selector: 'app-admin-partner-hierarchy-page',
  standalone: true,
  imports: [CommonModule, BadgeComponent, ConfirmDialogComponent],
  templateUrl: './admin-partner-hierarchy-page.component.html',
  styleUrls: ['./admin-partner-hierarchy-page.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class AdminPartnerHierarchyPageComponent {
  readonly facade = inject(AdminPartnerHierarchyFacade);

  readonly environments: Environment[] = ['TEST', 'LIVE'];

  /** Node pending a disable confirmation, or null when no dialog is open. */
  readonly pendingDisable = signal<ProvisioningNode | null>(null);

  constructor() {
    this.facade.load();
  }

  /** Indentation for a tree rendered as a flat list. */
  indentFor(depth: number): string {
    return `${depth * 1.5}rem`;
  }

  badgeVariantFor(status: NodeStatus): 'success' | 'warning' | 'neutral' {
    switch (status) {
      case 'active': return 'success';
      case 'suspended': return 'warning';
      case 'disabled': return 'neutral';
    }
  }

  levelLabel(level: string): string {
    return level.replace('_', ' ');
  }

  /**
   * Disable is terminal and cascades to every descendant, so it always goes
   * through a confirmation - there is no undo on the other side of it.
   */
  requestDisable(node: ProvisioningNode): void {
    this.pendingDisable.set(node);
  }

  confirmDisable(): void {
    const node = this.pendingDisable();
    if (node) {
      this.facade.disable(node.id);
    }
    this.pendingDisable.set(null);
  }

  cancelDisable(): void {
    this.pendingDisable.set(null);
  }
}
