import { STEPPER_GLOBAL_OPTIONS } from '@angular/cdk/stepper';
import { AfterViewChecked, ChangeDetectorRef, Component, OnInit, ViewChild, ViewContainerRef } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { MatStepper } from '@angular/material';
import { ActivatedRoute, Router } from '@angular/router';
import { TranslateService } from '@ngx-translate/core';
import { InitCommonsService, NotificationService, NotificationType } from '@xdf/commons';
import { AuditDialogService, ConfirmationDialogService, DynaDataService, IFormView, ValidatorUtils } from '@xdf/gallery';
import { NavigationService } from '@xdf/layouts';
import { ReservationService } from '../../service/reservation.service';
import { PassengerService } from '../../service/passenger.service';
import { TICKET_TYPES } from '../../interfaces/ticketType.interface';
import { TRAVEL_CLASSES } from '../../interfaces/travelClass.interface';

@Component({
  selector: 'byte-reservations',
  templateUrl: './reservations.component.html',
  styleUrls: ['./reservations.component.scss'],
  providers: [
    {
      provide: STEPPER_GLOBAL_OPTIONS,
      useValue: { showError: true }
    }
  ]
})
export class ReservationsComponent extends IFormView implements OnInit {
  protected getFields(): FormGroup {
    throw new Error('Method not implemented.');
  }

  @ViewChild('stepper', { static: true }) stepper: MatStepper;

  passengers: any[] = [];

  ticketTypes: any[] = TICKET_TYPES;
  travelClasses: any[] = TRAVEL_CLASSES;

  isLinear: boolean = false;

  personalInformationFormGroup: FormGroup;

  flightSelectedForm = this._formBuilder.group({
    flightId: ['', Validators.required]
  });

  public flightSelected: any;

  constructor(
    protected vcRef: ViewContainerRef,
    protected route: ActivatedRoute,
    protected router: Router,
    protected dynaDataService: DynaDataService,
    protected translate: TranslateService,
    protected notificationService: NotificationService,
    protected auditDialogService: AuditDialogService,
    protected confirmationDialogService: ConfirmationDialogService,
    protected navigationService: NavigationService,
    protected init: InitCommonsService,
    protected validatorUtils: ValidatorUtils,
    private readonly changeDetectorRef: ChangeDetectorRef,
    private activatedRouter: ActivatedRoute,
    private _formBuilder: FormBuilder,
    private reservationService: ReservationService,
    private passengerService: PassengerService
  ) {
    super(vcRef, route, router, dynaDataService, translate, notificationService, auditDialogService, confirmationDialogService, init);
  }

  ngOnInit() {
    this.icon = "<i class=\"fa fa-book fa-1_5x\"></i>";
    this.activatedRouter.params.subscribe(params => this.mode = params['mode']);
    this.ticketTypes = TICKET_TYPES;
    this.travelClasses = TRAVEL_CLASSES;
    this.getAllPassengers();
    this.getRecords();
    this.buildForm();
  }

  getRecords(): void {
    if (this.mode !== 'new') {
      this.route.queryParams.subscribe(params => {
        this.id = params['id'];
      });
      this.reservationService.getById(this.id)
        .subscribe(reservation => {
          this.flightSelectedForm.controls['flightId'].setValue(reservation.flightId);
          this.personalInformationFormGroup.controls['passenger'].setValue(reservation.passengerId);
          this.personalInformationFormGroup.controls['ticketType'].setValue(reservation.ticketType);
          this.personalInformationFormGroup.controls['travelClass'].setValue(reservation.travelClass);
          this.flightSelected = reservation.flightSearchBean;
        });
    }
  }

  buildForm(): void {
    this.personalInformationFormGroup = this._formBuilder.group({
      passenger: new FormControl({value: null, disabled: this.mode === 'view' || this.mode === 'edit'}, [Validators.required]),
      ticketType: new FormControl({value: null, disabled: this.mode === 'view' || this.mode === 'edit'}, [Validators.required]),
      travelClass: new FormControl({value: null, disabled: this.mode === 'view' || this.mode === 'edit'}, [Validators.required])
    });
  }


  getAllPassengers(): void {
    this.passengerService.getResultList()
    .subscribe(passengers => this.passengers = passengers);
  }

  get passengerName() {
    const passenger = this.passengers.find(passenger => passenger.value === this.personalInformationFormGroup.get('passenger').value);
    return passenger ? passenger.label : '';
  }
  get ticketTypeName() { return this.personalInformationFormGroup.get('ticketType').value; }
  get travelClassName() { return this.personalInformationFormGroup.get('travelClass').value; }

  optionEvent(option: any) {
    this.router.navigate(["/agent/reservations"]);
  }

  onFlightSelected(flight: any) {
    this.flightSelectedForm.controls['flightId'].setValue(flight.id);
    this.flightSelected = flight;
  }

  onSaveReservation() {
    const reservation = {
      agentId: 6,
      passengerId: this.personalInformationFormGroup.get('passenger').value,
      ticketType: this.personalInformationFormGroup.get('ticketType').value,
      travelClass: this.personalInformationFormGroup.get('travelClass').value,
      flightId: this.flightSelectedForm.get('flightId').value,
      departureDate: this.flightSelected.departureDate
    }
    this.reservationService.create(reservation)
      .subscribe(response => {
        this.notificationService.showMessage('Reservación creada exitosamente', 'Satisfactorio', NotificationType.success);
        this.router.navigate(["/agent/reservations"]);
      }, error => {
        this.notificationService.showMessage('Error al crear la reservación', 'Error', NotificationType.error);
      })
  }

}
