import 'package:medora/data/models/consultation_center.dart';

class ConsultationCenterController {
  final ConsultationCenter model;
  Map<String, String> validationErrors = {};

  ConsultationCenterController() : model = ConsultationCenter();

  // Address validation methods
  bool validatePostalCode(String postalCode) {
    if (postalCode.isEmpty || postalCode.length < 5) {
      validationErrors['postalCode'] = 'Invalid postal code';
      return false;
    }
    validationErrors.remove('postalCode');
    return true;
  }

  void updateFloorBuilding(String floorBuilding) {
    model.floorBuilding = floorBuilding;
  }

  void updateStreet(String street) {
    model.street = street;
  }

  void updateCity(String city) {
    model.city = city;
  }

  void updateState(String state) {
    model.state = state;
  }

  void updateCountry(String country) {
    model.country = country;
  }

  void updatePostalCode(String postalCode) {
    if (validatePostalCode(postalCode)) {
      model.postalCode = postalCode;
    }
  }

  void updateAddressType(String addressType) {
    model.addressType = addressType;
  }

  // New field updates
  void updateConsultationFee(String fee) {
    {
      model.consultationFee = fee;
    }
  }

  void updateAverageDuration(String minutes) {
    {
      model.averageDurationMinutes = minutes;
    }
  }

  void addTimeSlot(String day, TimeSlot slot) {
    // Validate the time slot (you can add your own validation logic)
    if (!_validateTimeSlot(slot)) {
      return;
    }
    // Ensure weeklySchedule is initialized
    model.weeklySchedule ??= [];

    // Find or create the day's schedule
    var daySchedule = model.weeklySchedule!.firstWhere(
      (schedule) => schedule.day == day,
      orElse: () {
        final newSchedule = AvailabilitySchedule(day: day, timeSlots: []);
        model.weeklySchedule!.add(newSchedule);
        return newSchedule;
      },
    );
    // Ensure timeSlots is initialized
    daySchedule.timeSlots ??= [];

    // Add the new time slot
    daySchedule.timeSlots!.add(slot);
  }

// Example validation method (customize as needed)
  bool _validateTimeSlot(TimeSlot slot) {
    // Add your validation logic here
    // For example, check that start time is before end time
    if (slot.startTime == null || slot.endTime == null) {
      return false;
    }

    // You can add more complex validation if needed
    return true;
  }

  void removeTimeSlot(String day, TimeSlot slot) {
    model.weeklySchedule
        ?.firstWhere((schedule) => schedule.day == day)
        .timeSlots
        ?.removeWhere((existing) =>
            existing.startTime == slot.startTime &&
            existing.endTime == slot.endTime);
  }
}
