import { Component, Input, Output, EventEmitter, OnInit, OnChanges, SimpleChanges } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { AvailabilityService, AvailabilityRequest, AvailabilityResponse, BulkAvailabilityRequest } from '../../../../services/availability.service';
import { ModalService } from '../../../../services/modal.service';
import { LoggerService } from '../../../../services/logger.service';

@Component({
  selector: 'app-availability',
  standalone: true,
  imports: [CommonModule, FormsModule],
  templateUrl: './availability.component.html',
  styleUrl: './availability.component.scss'
})
export class AvailabilityComponent implements OnInit, OnChanges {
  @Input() doctorId: string | null = null;
  @Output() availabilityChanged = new EventEmitter<void>();
  
  availability: AvailabilityResponse[] = [];
  showAvailabilityForm = false;
  showBulkAvailabilityForm = false;
  dayFilter: string = 'all';
  error: string | null = null;
  
  newAvailability: AvailabilityRequest = {
    doctorId: '',
    dayOfWeek: 'MONDAY',
    startTime: '09:00',
    endTime: '17:00'
  };
  
  bulkAvailability: BulkAvailabilityRequest = {
    doctorId: '',
    availabilities: []
  };

  constructor(
    private availabilityService: AvailabilityService,
    private modalService: ModalService,
    private logger: LoggerService
  ) {}

  ngOnInit() {
    if (this.doctorId) {
      this.newAvailability.doctorId = this.doctorId;
      this.bulkAvailability.doctorId = this.doctorId;
      this.loadAvailability();
    }
  }

  ngOnChanges(changes: SimpleChanges) {
    if (changes['doctorId'] && this.doctorId) {
      this.newAvailability.doctorId = this.doctorId;
      this.bulkAvailability.doctorId = this.doctorId;
      this.loadAvailability();
    }
  }

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

  async loadAvailability() {
    if (!this.doctorId) return;
    
    try {
      if (this.dayFilter !== 'all') {
        this.availability = await this.availabilityService.getAvailabilityByDay(this.doctorId, this.dayFilter);
      } else {
        this.availability = await this.availabilityService.getDoctorAvailability(this.doctorId);
      }
    } catch (e: any) {
      this.logger.error('Error loading availability:', e);
      this.availability = [];
    }
  }

  onDayFilterChange() {
    this.loadAvailability();
  }

  async createAvailability() {
    if (!this.newAvailability.doctorId || !this.newAvailability.startTime || !this.newAvailability.endTime) {
      this.error = 'Please fill in all required fields';
      return;
    }

    if (!this.doctorId) {
      this.error = 'Doctor ID not available';
      return;
    }

    this.newAvailability.doctorId = this.doctorId;
    this.error = null;

    try {
      await this.availabilityService.createAvailability(this.newAvailability);
      this.showAvailabilityForm = false;
      this.newAvailability = {
        doctorId: this.doctorId,
        dayOfWeek: 'MONDAY',
        startTime: '09:00',
        endTime: '17:00'
      };
      this.error = null;
      await this.loadAvailability();
      this.availabilityChanged.emit();
    } catch (e: any) {
      this.error = e?.response?.data?.message || e?.response?.data?.error || 'Failed to create availability slot';
    }
  }

  async deleteAvailability(availabilityId: string) {
    const confirmed = await this.modalService.confirm(
      'Are you sure you want to delete this availability slot?',
      'Delete Availability Slot',
      'Delete',
      'Cancel'
    );
    if (!confirmed) return;
    
    try {
      await this.availabilityService.deleteAvailability(availabilityId);
      await this.loadAvailability();
      this.availabilityChanged.emit();
    } catch (e: any) {
      this.error = e?.response?.data?.message || 'Failed to delete availability slot';
    }
  }

  async deleteAllAvailability() {
    if (!this.doctorId) {
      this.error = 'Doctor ID not available';
      return;
    }
    const confirmed = await this.modalService.confirm(
      'Are you sure you want to delete ALL availability slots? This action cannot be undone.',
      'Delete All Availability Slots',
      'Delete All',
      'Cancel'
    );
    if (!confirmed) return;
    
    try {
      await this.availabilityService.deleteAllDoctorAvailability(this.doctorId);
      await this.loadAvailability();
      this.availabilityChanged.emit();
    } catch (e: any) {
      this.error = e?.response?.data?.message || 'Failed to delete all availability slots';
    }
  }

  async createBulkAvailability() {
    if (!this.bulkAvailability.doctorId || !this.bulkAvailability.availabilities.length) {
      this.error = 'Please add at least one availability slot';
      return;
    }

    if (!this.doctorId) {
      this.error = 'Doctor ID not available';
      return;
    }

    this.bulkAvailability.doctorId = this.doctorId;
    this.error = null;

    try {
      await this.availabilityService.createBulkAvailability(this.bulkAvailability);
      this.showBulkAvailabilityForm = false;
      this.bulkAvailability = {
        doctorId: this.doctorId,
        availabilities: []
      };
      this.error = null;
      await this.loadAvailability();
      this.availabilityChanged.emit();
    } catch (e: any) {
      this.error = e?.response?.data?.message || e?.response?.data?.error || 'Failed to create bulk availability';
    }
  }

  addBulkAvailabilitySlot() {
    this.bulkAvailability.availabilities.push({
      dayOfWeek: 'MONDAY',
      startTime: '09:00',
      endTime: '17:00'
    });
  }

  removeBulkAvailabilitySlot(index: number) {
    this.bulkAvailability.availabilities.splice(index, 1);
  }
}