
import 'package:flutter/material.dart';
import 'package:hmg_patient_app_new/features/active_prescriptions/models/active_prescriptions_response_model.dart';
import 'package:hmg_patient_app_new/features/active_prescriptions/active_prescriptions_repo.dart';
import 'package:hmg_patient_app_new/services/error_handler_service.dart';

class ActivePrescriptionsViewModel extends ChangeNotifier {
  late ActivePrescriptionsRepo activePrescriptionsRepo;
  late ErrorHandlerService errorHandlerService;
  List<ActivePrescriptionsResponseModel> activePrescriptionsDetailsList = [];

  ActivePrescriptionsViewModel({
    required this.activePrescriptionsRepo,
    required this.errorHandlerService,
  });

  Future<void> getActiveMedications({
    Function(dynamic)? onSuccess,
    Function(String)? onError,
  }) async {
    final result =
    await activePrescriptionsRepo.getActivePrescriptionsDetails();
    result.fold(
          (failure) async =>
      await errorHandlerService.handleError(failure: failure),
          (apiResponse) {
        if (apiResponse.messageStatus == 1) {
          activePrescriptionsDetailsList = apiResponse.data ?? [];
          notifyListeners();
          if (onSuccess != null) onSuccess(apiResponse.data);
        }
      },
    );
  }

  DateTime parseDate(String? date) {
    if (date == null) return DateTime.now();
    final regex = RegExp(r"\/Date\((\d+)([+-]\d+)?\)\/");
    final match = regex.firstMatch(date);
    if (match != null) {
      final millis = int.parse(match.group(1)!);
      return DateTime.fromMillisecondsSinceEpoch(millis);
    }
    return DateTime.tryParse(date) ?? DateTime.now();
  }

  List<DateTime> generateMedicationDays(ActivePrescriptionsResponseModel med) {
    final start = parseDate(med.startDate);
    final duration = med.days ?? 0;
    if (duration <= 0) return [];
    final f = (med.frequency ?? "").toLowerCase().trim();
    int intervalDays = 1;

    if (f.contains("every six hours") ||
        f.contains("every 6 hours") ||
        f.contains("every four hours") ||
        f.contains("every 4 hours") ||
        f.contains("every eight hours") ||
        f.contains("every 8 hours") ||
        f.contains("every 12 hours") ||
        f.contains("every twelve hours") ||
        f.contains("every 24 hours") ||
        f.contains("3 times a day") ||
        f.contains("once a day")) {
      intervalDays = 1;
    }
    else if (f.contains("once a week")) {
      intervalDays = 7;
    }
    else if (f.contains("every 3 days")) {
      intervalDays = 3;
    }
    else if (f.contains("every other day")) {
      intervalDays = 2;
    }

    List<DateTime> result = [];
    for (int offset = 0; offset < duration; offset += intervalDays) {
      result.add(start.add(Duration(days: offset)));
    }

    return result;
  }

  bool sameYMD(DateTime a, DateTime b) =>
      a.year == b.year && a.month == b.month && a.day == b.day;

  List<ActivePrescriptionsResponseModel> getMedsForSelectedDay(
      DateTime selectedDate) {
    final clean = DateTime(selectedDate.year, selectedDate.month, selectedDate.day);

    return activePrescriptionsDetailsList.where((med) {
      final days = generateMedicationDays(med);
      return days.any((d) => sameYMD(d, clean));
    }).toList();
  }
}




