enum CarePlanPhase { active, upcoming, ended }

CarePlanPhase resolveCarePlanPhase({
  bool enabled = true,
  String? startDate,
  String? endDate,
  DateTime? today,
}) {
  if (!enabled) return CarePlanPhase.ended;

  final current = _dateOnly(today ?? DateTime.now());
  final start = DateTime.tryParse(startDate ?? '');
  final end = DateTime.tryParse(endDate ?? '');
  if (start != null && _dateOnly(start).isAfter(current)) {
    return CarePlanPhase.upcoming;
  }
  if (end != null && _dateOnly(end).isBefore(current)) {
    return CarePlanPhase.ended;
  }
  return CarePlanPhase.active;
}

String? validateMedicationForm({
  required String name,
  required String dosage,
  required List<String> times,
  required DateTime startDate,
  DateTime? endDate,
}) {
  if (name.trim().isEmpty) return '请输入药品名称';
  if (dosage.trim().isEmpty) return '请输入服药剂量';
  if (times.isEmpty) return '请至少设置一个服药时间';
  if (times.toSet().length != times.length) return '服药时间不能重复';
  if (endDate != null && _dateOnly(endDate).isBefore(_dateOnly(startDate))) {
    return '结束日期不能早于开始日期';
  }
  return null;
}

DateTime _dateOnly(DateTime value) =>
    DateTime(value.year, value.month, value.day);
