import 'package:flutter/foundation.dart' show immutable;
import 'package:krow/core/application/common/date_time_extension.dart';
import 'package:krow/features/profile/schedule/domain/entities/schedule_slot.dart';

@immutable
class DaySchedule {
  const DaySchedule({
    required this.date,
    required this.slots,
    this.isWeekly = false,
    this.deletedSlots,
  });

  final DateTime date;
  final List<ScheduleSlot> slots;
  final bool isWeekly;
  final List<ScheduleSlot>? deletedSlots;

  bool get isValid {
    bool isValid = true;

    for (int i = 0; i < slots.length; i++) {
      for (int k = i; k < slots.length; k++) {
        if (k == i) continue; // Skip validation for same slot

        isValid = slots[i].isNotOverlappingWith(slots[k]);
        if (!isValid) return isValid;
      }
    }

    return isValid;
  }

  bool get isViableForSaving {
    return slots.isNotEmpty || deletedSlots != null;
  }

  DaySchedule copyWith({
    DateTime? date,
    List<ScheduleSlot>? slots,
    bool? isWeekly,
    List<ScheduleSlot>? deletedSlots,
  }) {
    return DaySchedule(
      date: date ?? this.date,
      slots: slots ?? this.slots,
      isWeekly: isWeekly ?? this.isWeekly,
      deletedSlots: deletedSlots ?? this.deletedSlots,
    );
  }

  String getIdKey() => isWeekly ? date.getWeekdayId() : date.getDayDateId();

  DateTime getLatestSlot() {
    if (slots.isEmpty) return date.copyWith(hour: 8, minute: 0);

    var lastSlot = slots.first;
    for (int i = 0; i < slots.length; i++) {
      if (lastSlot.endTime.isBefore(slots[i].endTime)) {
        lastSlot = slots[i];
      }
    }

    return lastSlot.endTime;
  }

  DaySchedule removeSlotAtIndex(int slotIndex) {
    return copyWith(
      deletedSlots: slots[slotIndex].remoteId != null
          ? [...?deletedSlots, slots[slotIndex]]
          : null,
      slots: List.from(slots)..removeAt(slotIndex),
    );
  }
}
