
import {
  AfterViewInit,
  ChangeDetectionStrategy,
  Component,
  EventEmitter,
  Input,
  Output,
  ViewChild,
} from '@angular/core';
import { FormsModule, NgForm } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { MatIconModule } from '@angular/material/icon';
import { MatMenuModule } from '@angular/material/menu';
import { debounceTime, map, tap } from 'rxjs';
import {
  AccountingFilterArgs,
  AccountingState,
} from '../../../core/data-access/graphql/generated/generated';

@Component({
    changeDetection: ChangeDetectionStrategy.OnPush,
    selector: 'dks-accounting-lane-header-filter',
    template: `
@switch (state) {
  @case (AccountingState.Billable) {
    <button
      mat-icon-button
      [matMenuTriggerFor]="beforeBilledMenu"
      aria-label="Abrechenbar Filter button"
      >
      <mat-icon>filter_list</mat-icon>
    </button>
  }
  @case (AccountingState.PreparedForBilling) {
    <button
      mat-icon-button
      [matMenuTriggerFor]="beforeBilledMenu"
      aria-label="Abrechnung vorbereitet Filter button"
      >
      <mat-icon>filter_list</mat-icon>
    </button>
  }
  @case (AccountingState.Billed) {
    <button
      mat-icon-button
      [matMenuTriggerFor]="afterBilledMenu"
      aria-label="Abgerechnet Filter button"
      >
      <mat-icon>filter_list</mat-icon>
    </button>
  }
}
<form #form="ngForm">
  <mat-menu #beforeBilledMenu="matMenu">
    @for (item of filter.beforeBilled; track item) {
      <section
        mat-menu-item
        (click)="$event.stopPropagation()"
        >
        <mat-checkbox [(ngModel)]="item.checked" [name]="item.value">{{
          item.text
        }}</mat-checkbox>
      </section>
    }
  </mat-menu>
  <mat-menu #afterBilledMenu="matMenu">
    @for (item of filter.afterBilled; track item) {
      <section
        mat-menu-item
        (click)="$event.stopPropagation()"
        >
        <mat-checkbox [(ngModel)]="item.checked" [name]="item.value">{{
          item.text
        }}</mat-checkbox>
      </section>
    }
  </mat-menu>
</form>
`,
    styles: [],
    imports: [
    FormsModule,
    MatButtonModule,
    MatIconModule,
    MatMenuModule,
    MatCheckboxModule
]
})
export class AccountingLaneHeaderFilterComponent implements AfterViewInit {
  @Input() state!: AccountingState;
  @Output() filterChange = new EventEmitter<AccountingFilterArgs>();
  @ViewChild('form') form!: NgForm;

  AccountingState = AccountingState;

  ngAfterViewInit() {
    this.form.valueChanges
      ?.pipe(
        // debounce to avoid multiple calls during form initialisation
        debounceTime(10),
        map((form): AccountingFilterArgs => {
          return Object.entries(form)
            .filter(([, value]) => value)
            .map(([key]) => key)
            .reduce((acc, key) => {
              const [property, value] = key.split('.');
              return {
                ...acc,
                [property]: [...(acc?.[property] || []), value],
              };
            }, {} as Record<string, string[]>);
        }),
        // filter((obj) => Object.keys(obj).length > 0),
        tap((form) => this.filterChange.emit(form))
      )
      .subscribe();
  }

  filter = {
    beforeBilled: [
      {
        checked: false,
        value: 'deviation.both',
        text: 'Abweichungen in Abrechnungsbeträgen',
      },
      {
        checked: false,
        value: 'missing.information',
        text: 'Fehlende Informationen',
      },
      {
        checked: false,
        value: 'missing.documents',
        text: 'Fehlende Dokumente',
      },
    ],
    afterBilled: [
      {
        checked: false,
        value: 'deviation.both',
        text: 'alle Abweichungen',
      },
      {
        checked: false,
        value: 'deviation.neg',
        text: 'negative Abweichungen',
      },
      {
        checked: false,
        value: 'deviation.pos',
        text: 'positive Abweichungen',
      },
    ],
  };
}
