import { Component, Input, Output, EventEmitter, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { AppointmentService, Appointment } from '../../../../services/appointment.service';
import { ModalService } from '../../../../services/modal.service';

@Component({
  selector: 'app-appointments',
  standalone: true,
  imports: [CommonModule],
  templateUrl: './appointments.component.html',
  styleUrl: './appointments.component.scss'
})
export class AppointmentsComponent implements OnInit {
  @Input() appointments: Appointment[] = [];
  @Input() error: string | null = null;
  @Output() refreshRequested = new EventEmitter<void>();
  
  loading = false;

  constructor(
    private appointmentService: AppointmentService,
    private modalService: ModalService
  ) {}

  ngOnInit() {}

  formatDate(dateString: string): string {
    if (!dateString) return 'N/A';
    const date = new Date(dateString);
    return date.toLocaleDateString();
  }

  formatTime(timeString: string): string {
    if (!timeString) return 'N/A';
    return timeString.substring(0, 5); // Format HH:MM
  }

  getStatusClass(status: string): string {
    const statusLower = status?.toLowerCase() || '';
    if (statusLower === 'completed') return 'status-completed';
    if (statusLower === 'confirmed') return 'status-confirmed';
    if (statusLower === 'cancelled') return 'status-cancelled';
    return 'status-scheduled';
  }

  getUpcomingAppointments(): Appointment[] {
    const now = new Date();
    return this.appointments
      .filter(apt => {
        const aptDate = new Date(`${apt.scheduledDate}T${apt.scheduledTime}`);
        return aptDate >= now && apt.status !== 'CANCELLED' && apt.status !== 'COMPLETED';
      })
      .sort((a, b) => {
        const dateA = new Date(`${a.scheduledDate}T${a.scheduledTime}`);
        const dateB = new Date(`${b.scheduledDate}T${b.scheduledTime}`);
        return dateA.getTime() - dateB.getTime();
      });
  }

  getPastAppointments(): Appointment[] {
    const now = new Date();
    return this.appointments
      .filter(apt => {
        const aptDate = new Date(`${apt.scheduledDate}T${apt.scheduledTime}`);
        return aptDate < now || apt.status === 'CANCELLED' || apt.status === 'COMPLETED';
      })
      .sort((a, b) => {
        const dateA = new Date(`${a.scheduledDate}T${a.scheduledTime}`);
        const dateB = new Date(`${b.scheduledDate}T${b.scheduledTime}`);
        return dateB.getTime() - dateA.getTime();
      });
  }

  async confirmAppointment(appointment: Appointment) {
    if (!appointment.id) {
      this.error = 'Appointment ID not available. Backend needs to include ID in response.';
      return;
    }
    try {
      await this.appointmentService.confirmAppointment(appointment.id);
      this.refreshRequested.emit();
    } catch (e: any) {
      this.error = e?.response?.data?.message || 'Failed to confirm appointment';
    }
  }

  async cancelAppointment(appointment: Appointment) {
    if (!appointment.id) {
      this.error = 'Appointment ID not available. Backend needs to include ID in response.';
      return;
    }
    const confirmed = await this.modalService.confirm(
      'Are you sure you want to cancel this appointment?',
      'Cancel Appointment',
      'Cancel Appointment',
      'Keep Appointment'
    );
    if (!confirmed) return;
    
    try {
      await this.appointmentService.cancelAppointment(appointment.id);
      this.refreshRequested.emit();
    } catch (e: any) {
      this.error = e?.response?.data?.message || 'Failed to cancel appointment';
    }
  }

  async completeAppointment(appointment: Appointment) {
    if (!appointment.id) {
      this.error = 'Appointment ID not available. Backend needs to include ID in response.';
      return;
    }
    try {
      await this.appointmentService.completeAppointment(appointment.id);
      this.refreshRequested.emit();
    } catch (e: any) {
      this.error = e?.response?.data?.message || 'Failed to complete appointment';
    }
  }

  async deleteAppointment(appointment: Appointment) {
    if (!appointment.id) {
      this.error = 'Appointment ID not available. Backend needs to include ID in response.';
      return;
    }
    const confirmed = await this.modalService.confirm(
      'Are you sure you want to delete this appointment? This action cannot be undone.',
      'Delete Appointment',
      'Delete',
      'Cancel'
    );
    if (!confirmed) {
      return;
    }
    
    try {
      await this.appointmentService.deleteAppointment(appointment.id);
      this.refreshRequested.emit();
      this.error = null;
    } catch (e: any) {
      this.error = e?.response?.data?.message || e?.message || 'Failed to delete appointment';
    }
  }
}