
import {
  ChangeDetectionStrategy,
  ChangeDetectorRef,
  Component,
  computed,
  effect,
  EventEmitter,
  inject,
  Input,
  model,
  OnInit,
  Output,
  Signal,
} from '@angular/core';
import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input';
import { MatRadioModule } from '@angular/material/radio';
import {
  ApprovalState,
  DocumentInfo,
  Ticket,
  TicketValidationState,
  Tour,
} from '../../../core/data-access/graphql/generated/generated';
import { AuthService } from '../../../core/components/ms-authentication/auth.service';

@Component({
  changeDetection: ChangeDetectionStrategy.OnPush,
  selector: 'dks-ticket-user-action-required',
  template: `<div class="flex flex-col p-3">
      <form #form="ngForm" class="flex flex-col w-full">
        <div class="flex justify-end pt-4">
          <button mat-stroked-button class="mr-2" (click)="form.resetForm()">
            Zurücksetzen
          </button>
          <button
            mat-flat-button
            color="primary"
            [disabled]="form.invalid"
            (click)="saveForm()"
            >
            Speichern
          </button>
        </div>
        <div class="flex flex-col p-2">
          <label>Wird eine Genehmigung benötigt?</label>
          <mat-radio-group
            [(ngModel)]="formModel().approval.isNeeded"
            name="approvalNeeded"
            required
            >
            <mat-radio-button [value]="false"> Nein </mat-radio-button>
            <mat-radio-button [value]="true"> Ja </mat-radio-button>
          </mat-radio-group>
        </div>
        @if (
          (ticket.approvalState === ApprovalState.Required &&
          formModel().approval.isNeeded) ||
          (ticket.approvalState === ApprovalState.Unknown &&
          formModel().approval.isNeeded)
          ) {
          <div class="flex flex-col p-2">
            <label>Wer fragte die Genehmigung an?</label>
            <mat-radio-group
              [(ngModel)]="formModel().approval.whoRequested"
              name="who"
              required
              >
              <mat-radio-button value="Avicenna"> Avicenna </mat-radio-button>
              <mat-radio-button value="Kunde"> Kunde </mat-radio-button>
            </mat-radio-group>
          </div>
          <mat-form-field class="p-2">
            <mat-label>Name des Sachbearbeiters?</mat-label>
            <input
              type="text"
              matInput
              id="staff"
              [(ngModel)]="formModel().approval.answeredFrom"
              name="staff"
              required
              />
          </mat-form-field>
        }
    
        <div class="flex flex-col p-2">
          <label>Wo befindet sich der Transportschein?</label>
          <mat-radio-group
            [(ngModel)]="formModel().tdLocation"
            name="tdLocation"
            required
            >
            <mat-radio-button [value]="'company'"> Im Betrieb </mat-radio-button>
            <mat-radio-button [value]="'practice'">
              In der Praxis
            </mat-radio-button>
            <mat-radio-button [value]="'customer'">
              Beim Kunden
            </mat-radio-button>
            <mat-radio-button [value]="'uncertain'"> Unklar </mat-radio-button>
          </mat-radio-group>
        </div>
      </form>
    </div>`,
  imports: [
    MatButtonModule,
    MatIconModule,
    MatFormFieldModule,
    MatRadioModule,
    MatInputModule,
    FormsModule
],
})
export class TicketUserActionRequiredComponent implements OnInit {
  @Input() ticket!: Ticket & { tours: Tour[] };
  @Output() saveFormData = new EventEmitter();

  TicketState = TicketValidationState;
  ApprovalState = ApprovalState;

  formModel = model<DocumentInfo>({
    approval: {
      isNeeded: undefined,
      whoRequested: '',
      answeredFrom: '',
    },
    tdLocation: '',
  });
  staffName: Signal<string | undefined>;

  constructor() {
    const authService = inject(AuthService);
    this.staffName = computed(() => authService.activeAccount()?.name);
  }

  ngOnInit(): void {
    this.formModel.set({
      approval: {
        isNeeded: this.isApprovalNeeded(),
        whoRequested: this.ticket.documentInfo?.approval?.whoRequested || '',
        answeredFrom:
          this.ticket.documentInfo?.approval?.answeredFrom != ''
            ? this.ticket.documentInfo?.approval?.answeredFrom
            : this.staffName(),
      },
      tdLocation: this.ticket.documentInfo?.tdLocation || '',
    });
  }

  saveForm() {
    this.saveFormData.emit(this.formModel());
  }

  private isApprovalNeeded() {
    if (this.ticket.approvalState === ApprovalState.Required) {
      return true;
    } else if (this.ticket.approvalState === ApprovalState.Free) {
      return false;
    } else {
      return undefined;
    }
  }
}
