import { ChangeDetectionStrategy, Component, ContentChild, TemplateRef, input, output } from '@angular/core';
import { NgTemplateOutlet } from '@angular/common';
import { ButtonComponent } from '../button/button.component';

export interface KeyValueRowContext<T> {
  $implicit: T;
  index: number;
}

@Component({
  selector: 'app-key-value-editor',
  standalone: true,
  imports: [NgTemplateOutlet, ButtonComponent],
  templateUrl: './key-value-editor.component.html',
  styleUrl: './key-value-editor.component.scss',
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class KeyValueEditorComponent<T> {
  readonly rows = input.required<T[]>();
  readonly addLabel = input('Add');
  readonly removeLabel = input('Remove');
  readonly createRow = input.required<() => T>();

  readonly rowsChange = output<T[]>();

  @ContentChild(TemplateRef) rowTemplate: TemplateRef<KeyValueRowContext<T>> | null = null;

  protected addRow(): void {
    this.rowsChange.emit([...this.rows(), this.createRow()()]);
  }

  protected removeRow(index: number): void {
    this.rowsChange.emit(this.rows().filter((_, i) => i !== index));
  }
}
