import { Component, OnInit } from '@angular/core';
import { AlertController, ToastController } from '@ionic/angular';
import { Booking } from '../../models/booking.model';
import { BookingsService } from '../../services/bookings.service';
import { ClassesService } from '../../services/classes.service';

@Component({
  selector: 'app-bookings',
  templateUrl: './bookings.page.html',
  styleUrls: ['./bookings.page.scss'],
  standalone: false
})
export class BookingsPage implements OnInit {
  reservas: Booking[] = [];
  cargando = true;
  private clasesCache: { [id: string]: any } = {};

  constructor(
    private bookingsService: BookingsService,
    private classesService: ClassesService,
    private alertController: AlertController,
    private toastController: ToastController
  ) { }

  ngOnInit() {
    this.cargarReservas();
  }

  ionViewWillEnter() {
    this.cargarReservas();
  }

  cargarReservas() {
    this.cargando = true;
    this.bookingsService.getUserBookings().subscribe({
      next: (bookings) => {
        // Ordenar por fecha y mostrar primero las confirmadas
        this.reservas = bookings.sort((a, b) => {
          // Primero ordenar por estado (confirmadas primero)
          if (a.status === 'confirmed' && b.status !== 'confirmed') return -1;
          if (a.status !== 'confirmed' && b.status === 'confirmed') return 1;
          
          // Luego ordenar por fecha
          const dateA = new Date(a.date || '');
          const dateB = new Date(b.date || '');
          return dateA.getTime() - dateB.getTime();
        });
        
        // Prellenar el cache de clases para obtener fechas reales
        this.precargarClases();
        
        this.cargando = false;
      },
      error: (error) => {
        console.error('Error al cargar reservas', error);
        this.cargando = false;
      }
    });
  }

  private precargarClases() {
    // Obtener solo IDs únicos de clases
    const classIds = [...new Set(this.reservas.map(booking => 
      booking.gymClassId || booking.classId
    ).filter(id => id !== undefined && id !== null))];
    
    classIds.forEach(id => {
      this.classesService.getClassById(id).subscribe(gymClass => {
        if (gymClass) {
          this.clasesCache[id] = gymClass;
        }
      });
    });
  }

  obtenerFechaClase(booking: Booking): Date {
    // Si tenemos la clase en caché, usamos su fecha real
    const classId = booking.gymClassId || booking.classId;
    if (classId && this.clasesCache[classId]) {
      return this.clasesCache[classId].startTime;
    }
    // Si no, usamos la fecha de la reserva o bookingDate
    return booking.date || (booking.bookingDate ? new Date(booking.bookingDate) : new Date());
  }

  refrescarReservas(event: any) {
    this.bookingsService.getUserBookings().subscribe({
      next: (bookings) => {
        this.reservas = bookings;
        event.target.complete();
        this.precargarClases();
      },
      error: (error) => {
        console.error('Error al refrescar reservas', error);
        event.target.complete();
      }
    });
  }

  getStatusColor(status: string): string {
    switch (status) {
      case 'confirmed': return 'success';
      case 'cancelled': return 'danger';
      case 'pending': return 'warning';
      default: return 'medium';
    }
  }

  getStatusText(status: string): string {
    switch (status) {
      case 'confirmed': return 'Confirmada';
      case 'cancelled': return 'Cancelada';
      case 'pending': return 'Pendiente';
      default: return status;
    }
  }

  async confirmarCancelacion(booking: Booking) {
    const alert = await this.alertController.create({
      header: 'Confirmar Cancelación',
      message: `¿Estás seguro de que deseas cancelar tu reserva para la clase de ${booking.className}?`,
      buttons: [
        {
          text: 'No',
          role: 'cancel'
        },
        {
          text: 'Sí, Cancelar',
          handler: () => {
            this.cancelarReserva(booking.id);
          }
        }
      ]
    });

    await alert.present();
  }

  async cancelarReserva(bookingId: string) {
    this.bookingsService.cancelBooking(bookingId).subscribe({
      next: async (success) => {
        if (success) {
          const toast = await this.toastController.create({
            message: 'Reserva cancelada correctamente',
            duration: 2000,
            position: 'bottom',
            color: 'success'
          });
          toast.present();
          this.cargarReservas();
        } else {
          const toast = await this.toastController.create({
            message: 'No se pudo cancelar la reserva',
            duration: 2000,
            position: 'bottom',
            color: 'danger'
          });
          toast.present();
        }
      },
      error: async (error) => {
        console.error('Error al cancelar reserva', error);
        const toast = await this.toastController.create({
          message: 'Error al cancelar la reserva',
          duration: 2000,
          position: 'bottom',
          color: 'danger'
        });
        toast.present();
      }
    });
  }
  getClassImage(booking: Booking): string {
    // 1. Primero intentamos obtener la imagen directamente del objeto gymClass (backend)
    if (booking.gymClass && booking.gymClass.imageUrl) {
      return booking.gymClass.imageUrl;
    }
    
    // 2. Si no está en el objeto gymClass, intentamos desde el caché
    const classId = booking.gymClassId || booking.classId;
    if (classId && this.clasesCache[classId] && this.clasesCache[classId].imageUrl) {
      return this.clasesCache[classId].imageUrl;
    }
    
    // 3. Si no encontramos la imagen, fallback basado en el nombre
    const className = booking.className || (booking.gymClass ? booking.gymClass.name : '');
    const nameLower = className.toLowerCase();
    if (nameLower.includes('yoga')) {
      return 'https://cdn-icons-png.flaticon.com/512/3456/3456464.png';
    } else if (nameLower.includes('spin')) {
      return 'https://cdn-icons-png.flaticon.com/512/805/805504.png';
    } else if (nameLower.includes('pilates')) {
      return 'https://cdn-icons-png.flaticon.com/512/625/625454.png';
    } else if (nameLower.includes('zumba')) {
      return 'https://cdn-icons-png.flaticon.com/512/5776/5776440.png';
    } else if (nameLower.includes('cross')) {
      return 'https://cdn-icons-png.flaticon.com/512/372/372612.png';
    }
    
    // Imagen por defecto
    return 'https://cdn-icons-png.flaticon.com/512/42/42829.png';
  }
}