import { ChangeDetectionStrategy, Component, inject } from '@angular/core';
import { MatIconModule } from '@angular/material/icon';
import { MatTabsModule } from '@angular/material/tabs';
import { DialogRef } from '@ngneat/dialog';
import { HotToastService } from '@ngxpert/hot-toast';
import { tap } from 'rxjs';
import {
  ApprovalState,
  SetDocumentInfoMutationVariables,
  Ticket,
  TicketValidationState,
} from '../../../core/data-access/graphql/generated/generated';
import { TicketsService } from '../tickets.service';
import { TicketDocumentsMissingComponent } from './ticket-documents-missing.component';
import { TicketOverviewComponent } from './ticket-overview.component';
import { TicketTdUncertainComponent } from './ticket-td-uncertain.component';
import { TicketToursComponent } from './ticket-tours.component';
import { TicketUserActionRequiredComponent } from './ticket-user-action-required.component';

@Component({
  changeDetection: ChangeDetectionStrategy.OnPush,
  selector: 'dks-ticket-view',
  templateUrl: './ticket-view.component.html',
  imports: [
    MatTabsModule,
    MatIconModule,
    TicketOverviewComponent,
    TicketToursComponent,
    TicketUserActionRequiredComponent,
    TicketTdUncertainComponent,
    TicketDocumentsMissingComponent,
  ],
})
export class TicketViewComponent {
  private ticketsService = inject(TicketsService);
  private toast = inject(HotToastService);

  ref: DialogRef<Ticket, undefined | any> = inject(DialogRef);

  TicketState = TicketValidationState;
  ApprovalState = ApprovalState;

  setDocumentInfo({
    approval,
    tdLocation,
  }: Omit<SetDocumentInfoMutationVariables, 'ticketId'>): void {
    this.ticketsService
      .setDocumentInfo(this.ref.data.id, {
        ...(this.ref.data?.documentInfo ?? {}),
        tdLocation,
        approval: {
          ...(this.ref.data?.documentInfo?.approval ?? {}),
          ...approval,
        },
      })
      .pipe(
        tap(() => this.toast.success(`Ticket aktualisiert`)),
        tap(() => this.ref.close())
      )
      .subscribe();
  }
}
