import { Component, input, output, signal } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { CheckboxComponent } from '@shared/ui/checkbox/checkbox.component';
import { ButtonComponent } from '@shared/ui/button/button.component';
import { LibraryPassage } from '@brief/domain/brief';

/** Molecule: multi-select list of the section's library passages. One "Voeg toe"
    inserts ALL checked passages at once (a single message upstream) — there is no
    single-insert path. Presentational: emits the chosen passages in list order. */
@Component({
  selector: 'app-passage-picker',
  imports: [FormsModule, CheckboxComponent, ButtonComponent],
  styles: [
    `
      :host {
        display: block;
        border: var(--rhc-border-width-sm) solid var(--rhc-color-border-default);
        border-radius: var(--rhc-border-radius-md);
        padding: var(--rhc-space-max-md);
      }
      ul {
        list-style: none;
        margin: 0 0 var(--rhc-space-max-md);
        padding: 0;
        display: grid;
        gap: var(--rhc-space-max-sm);
      }
      .scope {
        color: var(--rhc-color-foreground-subtle);
      }
    `,
  ],
  template: `
    <ul>
      @for (p of passages(); track p.passageId) {
        <li>
          <app-checkbox
            [label]="p.label"
            [ngModel]="!!checked()[p.passageId]"
            (ngModelChange)="set(p.passageId, $event)"
          />
          <span class="scope"> · {{ p.scope === 'beroep' ? beroepLabel() : globalLabel() }}</span>
        </li>
      }
    </ul>
    <app-button variant="secondary" [disabled]="count() === 0" (click)="add()"
      >{{ addLabel() }} ({{ count() }})</app-button
    >
  `,
})
export class PassagePickerComponent {
  passages = input.required<readonly LibraryPassage[]>();
  insert = output<LibraryPassage[]>();

  addLabel = input($localize`:@@brief.picker.add:Voeg toe`);
  globalLabel = input($localize`:@@brief.picker.global:algemeen`);
  beroepLabel = input($localize`:@@brief.picker.beroep:beroepsspecifiek`);

  protected checked = signal<Record<string, boolean>>({});
  protected count = () => Object.values(this.checked()).filter(Boolean).length;

  protected set(id: string, on: boolean) {
    this.checked.update((c) => ({ ...c, [id]: on }));
  }

  protected add() {
    const chosen = this.passages().filter((p) => this.checked()[p.passageId]);
    if (chosen.length) {
      this.insert.emit(chosen);
      this.checked.set({});
    }
  }
}
