import { Component, OnInit, ElementRef, ViewChild } from '@angular/core';
import { Router } from '@angular/router';
import Swal from 'sweetalert2';
import { ReservasService } from '../../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 = '';
  reservas: any[] = [];

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

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

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

  eliminar(event:any, id: number){
    event.stopPropagation();
    Swal.fire({
      title: 'Estas seguro?' + ' Pasajero ID: ' + id,
      text: "No se podran revertir los cambios!",
      icon: 'warning',
      showCancelButton: true,
      confirmButtonColor: '#3085d6',
      cancelButtonColor: '#d33',
      confirmButtonText: 'Si, eliminar!',
      cancelButtonText: 'Cancelar'
    }).then((result) => {
      if (result.isConfirmed) {
        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 elimino correctamente'
        })
      }
    })
  }

  detalles(id:number){
    this.router.navigate(['/reservas/detalles/',id ]);
  }

  actualizar(id: number){
    this.router.navigate(['/pasajeros/agregar/',id ]);
  }

  public getReservas(){
    this.reservasService.getReservas().subscribe(
      res => {
        this.reservas = res;
        this.dataSource = new MatTableDataSource(this.reservas);
        this.dataSource.paginator = this.paginator;  
        this.dataSource.sort = this.sort;
      }
    )
  }

  cambiarEstadoReserva(event:any,idReserva: number){
    event.stopPropagation();
    Swal.fire({
      title: 'Cancelar la reserva?' + ' ReservaID: ' + idReserva,
      icon: 'warning',
      showCancelButton: true,
      confirmButtonColor: '#3085d6',
      cancelButtonColor: '#d33',
      confirmButtonText: 'Si',
      cancelButtonText: 'Cancelar'
    }).then((result) => {
      if (result.isConfirmed) {
        this.updateEstado(idReserva);
      }
    })
    this.getReservas();
  }

  updateEstado(idReserva: number){

    let query = {
      estado: 'cancelado'
    }

    this.reservasService.updateEstadoReserva(idReserva,query).subscribe(
      res =>{
        this.getReservas();
        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 cancelo correctamente'
        })
      }
    )
  }

  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();
    }
  }

}
