import { Component, EventEmitter, Input, Output, ChangeDetectionStrategy } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { Appointment } from '../../../../services/appointment.service';

interface AppointmentDraft {
  doctorId: string;
  scheduledDate: string;
  scheduledTime: string;
}

@Component({
  selector: 'app-patient-appointments-panel',
  standalone: true,
  imports: [CommonModule, FormsModule],
  templateUrl: './patient-appointments-panel.component.html',
  styleUrls: ['./patient-appointments-panel.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class PatientAppointmentsPanelComponent {
  @Input() appointments: Appointment[] = [];
  @Input() doctors: any[] = [];
  @Input() newAppointment: AppointmentDraft = { doctorId: '', scheduledDate: '', scheduledTime: '' };
  @Input() showRequestForm = false;
  @Input() availableSlots: string[] = [];
  @Input() loadingSlots = false;
  @Input() selectedDate = '';
  @Input() upcomingAppointments: Appointment[] = [];
  @Input() pastAppointments: Appointment[] = [];
  @Input() minDate = '';
  @Input() formatDateFn: (value: string) => string = (value: string) => value;
  @Input() formatTimeFn: (value: string) => string = (value: string) => value;

  @Output() toggleRequestForm = new EventEmitter<boolean>();
  @Output() requestAppointment = new EventEmitter<void>();
  @Output() doctorChange = new EventEmitter<void>();
  @Output() dateChange = new EventEmitter<void>();
  @Output() selectSlot = new EventEmitter<string>();
  @Output() cancelAppointment = new EventEmitter<Appointment>();
  @Output() deleteAppointment = new EventEmitter<Appointment>();

  onToggleRequestForm(open?: boolean): void {
    this.toggleRequestForm.emit(open ?? !this.showRequestForm);
  }

  onSubmitRequest(): void {
    this.requestAppointment.emit();
  }

  onDoctorChange(): void {
    this.doctorChange.emit();
  }

  onDateChange(): void {
    this.dateChange.emit();
  }

  onSelectSlot(slot: string): void {
    this.selectSlot.emit(slot);
  }

  onCancelAppointment(appointment: Appointment): void {
    this.cancelAppointment.emit(appointment);
  }

  onDeleteAppointment(appointment: Appointment): void {
    this.deleteAppointment.emit(appointment);
  }

  statusClass(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';
  }
}

