
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, filter, map, tap } from 'rxjs';
import {
  ApprovalState,
  TicketFilterArgs,
  TicketValidationState,
} from '../../../core/data-access/graphql/generated/generated';

@Component({
    changeDetection: ChangeDetectionStrategy.OnPush,
    selector: 'dks-ticket-lane-header-filter',
    template: `
@switch (state) {
  @case (TicketValidationState.Created) {
    <button
      mat-icon-button
      [matMenuTriggerFor]="createdMenu"
      aria-label="Touren angenommen Filter button"
      >
      <mat-icon>filter_list</mat-icon>
    </button>
  }
  @case (TicketValidationState.UserInteractionRequired) {
    <button
      mat-icon-button
      [matMenuTriggerFor]="userInteractionMenu"
      aria-label="Touren angenommen Filter button"
      >
      <mat-icon>filter_list</mat-icon>
    </button>
  }
  @case (TicketValidationState.TdUncertain) {
    <button
      mat-icon-button
      [matMenuTriggerFor]="tdUncertainMenu"
      aria-label="Touren angenommen Filter button"
      >
      <mat-icon>filter_list</mat-icon>
    </button>
  }
  @case (TicketValidationState.DocumentsMissing) {
    <button
      mat-icon-button
      [matMenuTriggerFor]="documentsMenu"
      aria-label="Touren angenommen Filter button"
      >
      <mat-icon>filter_list</mat-icon>
    </button>
  }
}
<form #form="ngForm">
  <mat-menu #createdMenu="matMenu">
    @for (item of filter.errors; 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 #userInteractionMenu="matMenu">
    @for (item of filter.approvalStates; 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 #tdUncertainMenu="matMenu">
    <section mat-menu-item>
      <mat-checkbox checked="true" disabled="true">Alle</mat-checkbox>
    </section>
  </mat-menu>
  <mat-menu #documentsMenu="matMenu">
    @for (item of filter.documentInfo; 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 TicketLaneHeaderFilterComponent implements AfterViewInit {
  @Input() state!: TicketValidationState;
  @Output() filterChange = new EventEmitter<TicketFilterArgs>();
  @ViewChild('form') form!: NgForm;

  TicketValidationState = TicketValidationState;

  ngAfterViewInit() {
    this.form.valueChanges
      ?.pipe(
        // debounce to avoid multiple calls during form initialisation
        debounceTime(10),
        map((form): TicketFilterArgs => {
          const filterKey = this.getFilterKeyForState();
          if (!filterKey) return {};

          return {
            [filterKey]: this.getFilterForState()
              .filter(({ value }) => form[value])
              .map(({ value }) => value),
          };
        }),
        filter((obj) => Object.keys(obj).length > 0),
        tap((form) => this.filterChange.emit(form))
      )
      .subscribe();
  }

  private getFilterForState() {
    switch (this.state) {
      case TicketValidationState.Created:
        return this.filter.errors;
      case TicketValidationState.UserInteractionRequired:
        return this.filter.approvalStates;
      case TicketValidationState.DocumentsMissing:
        return this.filter.documentInfo;
      case TicketValidationState.TdUncertain:
      case TicketValidationState.Archived:
        return [];
    }
  }

  private getFilterKeyForState() {
    switch (this.state) {
      case TicketValidationState.Created:
        return 'errors';
      case TicketValidationState.UserInteractionRequired:
        return 'approvalStates';
      case TicketValidationState.DocumentsMissing:
        return 'documentInfo';
      case TicketValidationState.TdUncertain:
      case TicketValidationState.Archived:
        return '';
    }
  }

  filter = {
    approvalStates: [
      {
        checked: false,
        value: ApprovalState.Free,
        text: 'Genehmigungsfrei',
      },
      {
        checked: false,
        value: ApprovalState.Required,
        text: 'Genehmigungspflichtig',
      },
      {
        checked: false,
        value: ApprovalState.Unknown,
        text: 'Genehmigung unklar',
      },
    ],
    errors: [
      {
        checked: false,
        value: 'Patient: Krankenkasse ist nicht gefüllt',
        text: 'Patient: Krankenkasse ist nicht gefüllt',
      },
    ],
    documentInfo: [
      // {
      //   checked: false,
      //   value: 'approval',
      //   text: 'Genehmigung fehlt',
      // },
      {
        checked: false,
        value: 'td_company',
        text: 'Transportschein im Betrieb',
      },
      {
        checked: false,
        value: 'td_customer',
        text: 'Transportschein beim Kunden',
      },
    ],
  };
}
