import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, FormControl, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { ReservasService } from '../../../reservas/services/reservas.service';
import { PagoReservaService } from '../../services/pago-reserva.service';
import Swal from 'sweetalert2';
import {MomentDateAdapter, MAT_MOMENT_DATE_ADAPTER_OPTIONS} from '@angular/material-moment-adapter';
import * as _moment from 'moment';
import { Moment} from 'moment';
import { DateAdapter, MAT_DATE_FORMATS, MAT_DATE_LOCALE } from '@angular/material/core';
import { MatDatepicker } from '@angular/material/datepicker';

const moment = _moment;

export const MY_FORMATS = {
  parse: {
    dateInput: 'MM/YYYY',
  },
  display: {
    dateInput: 'MM/YYYY',
    monthYearLabel: 'MMM YYYY',
    dateA11yLabel: 'LL',
    monthYearA11yLabel: 'MMMM YYYY',
  },
};

@Component({
  selector: 'app-pagar',
  templateUrl: './pagar.component.html',
  styleUrls: ['./pagar.component.css'],
  providers: [
    {
      provide: DateAdapter,
      useClass: MomentDateAdapter,
      deps: [MAT_DATE_LOCALE, MAT_MOMENT_DATE_ADAPTER_OPTIONS]
    },

    {provide: MAT_DATE_FORMATS, useValue: MY_FORMATS},
  ],
})
export class PagarComponent implements OnInit{

  id: number = 0;
  idPago: number = 0;

  reservaForm: FormGroup = this.formBuilder.group({
    pasajeroNombre: [ ''  ],
    agenteNombre: [ ''],
    idReserva: [ '' ],
    costo: ['']
  });

  pagoForm: FormGroup = this.formBuilder.group({
    numeroTarjeta: [ '' ],
    nombreTitular: [ ''  ],
    fechaVencimiento: [''],
    ccv: [ '' ]
  });

  date = new FormControl(moment(),Validators.required);

  constructor(
   private formBuilder: FormBuilder,
   private activatedRoute: ActivatedRoute,
   private reservasService: ReservasService,
   private pagoReservaService: PagoReservaService,
   private router: Router
  ){}

  ngOnInit(): void {
    this.id = this.activatedRoute.snapshot.params['id'];
    this.reservasService.getReserva(this.id).subscribe(
      res =>{
        this.reservaForm.controls['pasajeroNombre'].setValue(res.pasajeroNombre);
        this.reservaForm.controls['agenteNombre'].setValue(res.agenteNombre);
        this.reservaForm.controls['idReserva'].setValue(this.id);
        this.reservaForm.controls['costo'].setValue(res.escalas[0].costo);
      }
    )

  }

  pagarReserva(){
    console.log(this.date.value);
    if (this.pagoForm.invalid || this.date.invalid) {
      this.pagoForm.markAllAsTouched();
      return;
    }
    this.agregarPago();
    const Toast = Swal.mixin({
      toast: true,
      position: 'top-end',
      showConfirmButton: false,
      timer: 2000,
      timerProgressBar: true,
      didOpen: (toast) => {
        toast.addEventListener('mouseenter', Swal.stopTimer)
        toast.addEventListener('mouseleave', Swal.resumeTimer)
      }
    })
    Toast.fire({
      icon: 'success',
      title: 'Se pago Correctamente'
    })
    this.irAlListado();
  }

  agregarPago(){
    let query = {
      pago: this.reservaForm.controls['costo'].value,
      estado: "pagado"
    }
    this.pagoReservaService.addPago(query).subscribe(
      res =>{
        this.idPago = res.id;
        this.agregarPagoAReserva(res.id);
        console.log(res.id);
      }
    )
  }

  agregarPagoAReserva(idPago: number){
    let query = {
      id: idPago
    }
    this.pagoReservaService.addPagoAReserva(this.id,query).subscribe(
      res => {
        this.actualizarEstadoReserva();
      }
    )
  }

  actualizarEstadoReserva(){   
    let query = {
      estado:  "aprobado",
    }
    this.reservasService.updateEstadoReserva(this.id,query).subscribe(
      res => {
      }
    )
  }

  private irAlListado(){
    this.router.navigate(['/pago-reserva/listado']);
  }

  chosenYearHandler(normalizedYear: Moment) {
    const ctrlValue = this.pagoForm.value.fechaVencimiento;
    ctrlValue!.year(normalizedYear.year());
    this.date.setValue(ctrlValue);
  }

  chosenMonthHandler(normalizedMonth: Moment, datepicker: MatDatepicker<Moment>) {
    const ctrlValue = this.date.value;
    ctrlValue!.month(normalizedMonth.month());
    this.date.setValue(ctrlValue);
    datepicker.close();
  }

}
