import 'dart:async' show FutureOr;

import 'package:flutter/foundation.dart' show ChangeNotifier;
import 'package:hmg_patient_app_new/core/app_state.dart';
import 'package:hmg_patient_app_new/core/location_util.dart';
import 'package:hmg_patient_app_new/features/emergency_services/emergency_services_repo.dart';
import 'package:hmg_patient_app_new/features/emergency_services/model/resp_model/ProjectAvgERWaitingTime.dart';
import 'package:hmg_patient_app_new/presentation/emergency_services/nearest_er_page.dart';
import 'package:hmg_patient_app_new/services/navigation_service.dart';
import 'package:hmg_patient_app_new/widgets/routes/custom_page_route.dart';
import 'package:url_launcher/url_launcher.dart' show canLaunchUrl, launchUrl, LaunchMode;

class EmergencyServicesViewModel extends ChangeNotifier {
  final NavigationService navServices;
  final LocationUtils? locationUtils;
  final EmergencyServicesRepo viewModel;
  final AppState appState;
  bool isERListLoading = false;
  List<ProjectAvgERWaitingTime> nearestERList = [];
  List<ProjectAvgERWaitingTime> nearestERFilteredList = [];

  EmergencyServicesViewModel(
      {required this.navServices,
      required this.locationUtils,
      required this.viewModel,
      required this.appState});

  void navigateToNearestERPage() {
    locationUtils!.getLocation(
        isShowConfirmDialog: true,
        onSuccess: (position) {
          navServices.push(
            CustomPageRoute(
              page: NearestErPage(),
            ),
          );
          getNearestER();
        });
  }

  void filterErList(String query) {
    print ("the query is $query");
    if (query.isEmpty) {
      nearestERFilteredList = nearestERList;
    } else {
      nearestERFilteredList = nearestERList
          .where((er) =>
              er.projectName != null &&
              er.projectName!.toLowerCase().contains(query.toLowerCase()))
          .toList();
    }
    notifyListeners();
  }

  // Open directions (navigation) from current location to destination.
  Future<void> openDirections({
    required double destLat,
    required double destLng,
    String? travelMode, // driving, walking, bicycling, transit
  }) async {
    // Try Google Maps app navigation intent (android/iOS)
    final modeParam = travelMode == null ? 'driving' : travelMode;
    final googleNavUri = Uri.parse('google.navigation:q=$destLat,$destLng&mode=${modeParam.substring(0,1)}'); // mode: d/w/b/t by scheme
    final universalUrl = Uri.parse('https://www.google.com/maps/dir/?api=1&destination=$destLat,$destLng&travelmode=$modeParam');

    if (await canLaunchUrl(googleNavUri)) {
      await launchUrl(googleNavUri, mode: LaunchMode.externalApplication);
    } else {
      await launchUrl(universalUrl, mode: LaunchMode.externalApplication);
    }
  }

  Future<void> openDialer(String phoneNumber) async {
    final Uri telUri = Uri(scheme: 'tel', path: phoneNumber);

    if (await canLaunchUrl(telUri)) {
      await launchUrl(telUri, mode: LaunchMode.externalApplication);
    } else {
      throw 'Could not open dialer for $phoneNumber';
    }
  }
  FutureOr<void> getNearestER() async {
    isERListLoading = true;
    nearestERList = [];
    nearestERFilteredList = [];
    notifyListeners();
    var response = await viewModel.getNearestEr();
    isERListLoading = false;
    notifyListeners();

    response.fold(
      (failure) async {
      },
      (apiResponse) {
        isERListLoading = false;
        if (apiResponse.messageStatus == 1) {
          nearestERList = apiResponse.data!;
          nearestERFilteredList = nearestERList;
        }
      },
    );
  }
}
