import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { PageEvent } from '@angular/material/paginator';
import { Router } from '@angular/router';
import Swal from 'sweetalert2';
import { ReservasService } from '../../../reservas/services/reservas.service';
import {MatPaginator} from '@angular/material/paginator';
import {MatSort} from '@angular/material/sort';
import {MatTableDataSource} from '@angular/material/table';
@Component({
  selector: 'app-listar',
  templateUrl: './listar.component.html',
  styleUrls: ['./listar.component.css']
})
export class ListarComponent implements OnInit{

  displayedColumns: string[] = ['id', 'agente','pasajero', 'monto', 'estado', 'opciones'];
  dataSource!: MatTableDataSource<any>;
  @ViewChild(MatSort) sort!: MatSort;
  @ViewChild(MatPaginator) paginator!: MatPaginator;
  @ViewChild('input') entradaFiltro: ElementRef | undefined;

  filtroInput: string = '';
  idPasajero: number =  parseInt(localStorage.getItem('id')!);
  claseBoton: string = '';
  reservaciones: any[] = [];

  constructor(
    private router: Router,
    private reservasService: ReservasService
  ){}

  ngOnInit(): void {
    setTimeout(() => {
      this.getReservaByIdPasajero();
    },300);
  }

  getClaseBoton(estado: string): string{
    switch( estado ) {
      case 'pendiente': 
        return 'btn-warning';
      
      case 'cancelado':
        return 'btn-danger';
      
      case 'aprobado':
        return 'btn-primary';
  
      default:
        return '';
    }
  }

  eliminar(event:any, id: number){
    event.stopPropagation();
    this.router.navigate(['/pago-reserva/pagar/',id ]);
  }

  detalles(id:number){
    this.router.navigate(['/pago-reserva/detalles/',id ]);
  }
  actualizar(id: number){
    this.router.navigate(['/agentes/agregar/',id ]);
  }

  getReservaByIdPasajero(){
    this.reservasService.getReservaByPasajeroId(this.idPasajero).subscribe(
      res => {
        this.reservaciones = res;
        this.dataSource = new MatTableDataSource(this.reservaciones);
        this.dataSource.paginator = this.paginator;  
        this.dataSource.sort = this.sort;
      }
    )
  }

  aplicarFiltro(event: Event) {
    const filterValue = this.filtroInput;
    this.dataSource.filter = filterValue.trim().toLowerCase();

    if (this.dataSource.paginator) {
      this.dataSource.paginator.firstPage();
    }
  }

  eliminarFiltros(){
    this.filtroInput = '';
    this.dataSource.filter = '';
    if (this.dataSource.paginator) {
      this.dataSource.paginator.firstPage();
    }
  }
  
}
