import 'dart:async';

import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_map/flutter_map.dart';
import 'package:flutter_map/plugin_api.dart';
import 'package:flutter_polyline_points/flutter_polyline_points.dart';
import 'package:geojson/geojson.dart';
import 'package:get/get.dart';
import 'package:latlong2/latlong.dart';
import 'package:rogapp/model/destination.dart';
import 'package:rogapp/pages/destination/destination_controller.dart';
import 'package:rogapp/routes/app_pages.dart';
import 'package:rogapp/services/auth_service.dart';
import 'package:rogapp/services/location_service.dart';
import 'package:rogapp/utils/database_helper.dart';
import 'package:shared_preferences/shared_preferences.dart';

class IndexController extends GetxController {
  List<GeoJsonFeatureCollection> locations = <GeoJsonFeatureCollection>[].obs;
  List<GeoJsonFeature> currentFeature = <GeoJsonFeature>[].obs;
  List<Destination> currentDestinationFeature = <Destination>[].obs;
  List<dynamic> perfectures = <dynamic>[].obs;
  List<LatLngBounds> currentBound = <LatLngBounds>[].obs;
  List<dynamic> subPerfs = <dynamic>[].obs;
  List<dynamic> areas = <dynamic>[].obs;
  List<dynamic> customAreas = <dynamic>[].obs;
  List<dynamic> cats = <dynamic>[].obs;

  List<String> currentCat = <String>[].obs;

  List<Map<String, dynamic>> currentUser = <Map<String, dynamic>>[].obs;
  List<dynamic> currentAction = <dynamic>[].obs;
  List<PointLatLng> routePoints = <PointLatLng>[].obs;
  var routePointLenght = 0.obs;

  double currentLat = 0.0, currentLon = 0.0;

  var isLoading = false.obs;

  var isRogMapcontrollerLoaded = false.obs;

  var isCustomAreaSelected = false.obs;

  MapController mapController = MapController();
  MapController rogMapController = MapController();

  String? userToken;

  // mode = 0 is map mode, mode = 1 list mode
  var mode = 0.obs;

  // master mode, rog or selection
  var rogMode = 1.obs;

  var desinationMode = 1.obs;

  bool showPopup = true;

  String dropdownValue = "9";
  String subDropdownValue = "-1";
  String areaDropdownValue = "-1";
  String cateogory = "-all-";

  ConnectivityResult connectionStatus = ConnectivityResult.none;
  var connectionStatusName = "".obs;
  final Connectivity _connectivity = Connectivity();
  late StreamSubscription<ConnectivityResult> _connectivitySubscription;

  void toggleMode() {
    if (mode.value == 0) {
      mode += 1;
    } else {
      mode -= 1;
    }
  }

  void toggleDestinationMode() {
    if (desinationMode.value == 0) {
      desinationMode.value += 1;
    } else {
      desinationMode.value -= 1;
    }
  }

  void switchPage(String page) {
    ////print("######## ${currentUser[0]["user"]["id"]}");
    switch (page) {
      case AppPages.INDEX:
        {
          rogMode.value = 0;
          //print("-- rog mode is ctrl is ${rog_mode.value}");
          Get.toNamed(page);
        }
        break;
      case AppPages.TRAVEL:
        {
          rogMode.value = 1;
          //Get.back();
          //Get.off(DestnationPage(), binding: DestinationBinding());
        }
        break;
      case AppPages.LOGIN:
        {
          rogMode.value = 2;
          Get.toNamed(page);
        }
        break;
      default:
        {
          rogMode.value = 1;
          Get.toNamed(AppPages.INDEX);
        }
    }
  }

  @override
  void onInit() {
    _connectivitySubscription =
        _connectivity.onConnectivityChanged.listen(_updateConnectionStatus);
    super.onInit();
  }

  @override
  void onClose() {
    _connectivitySubscription.cancel();
    super.onClose();
  }

  Future<void> _updateConnectionStatus(ConnectivityResult result) async {
    connectionStatus = result;
    connectionStatusName.value = result.name;
  }

  Future<void> initConnectivity() async {
    late ConnectivityResult result;
    // Platform messages may fail, so we use a try/catch PlatformException.
    try {
      result = await _connectivity.checkConnectivity();
    } on PlatformException catch (_) {
      //print('Couldn\'t check connectivity status --- $e');
      return;
    }

    return _updateConnectionStatus(result);
  }

  LatLngBounds boundsFromLatLngList(List<LatLng> list) {
    double? x0, x1, y0, y1;
    for (LatLng latLng in list) {
      if (x0 == null || x1 == null || y0 == null || y1 == null) {
        x0 = x1 = latLng.latitude;
        y0 = y1 = latLng.longitude;
      } else {
        if (latLng.latitude > x1) x1 = latLng.latitude;
        if (latLng.latitude < x0) x0 = latLng.latitude;
        if (latLng.longitude > y1) y1 = latLng.longitude;
        if (latLng.longitude < y0) y0 = latLng.longitude;
      }
    }

    return LatLngBounds(LatLng(x1!, y1!), LatLng(x0!, y0!));
  }

  void login(String email, String password, BuildContext context) {
    AuthService.login(email, password).then((value) {
      //print("------- logged in user details ######## $value ###### --------");
      if (value.isNotEmpty) {
        Navigator.pop(context);
        //print("--------- user details login ----- $value");
        changeUser(value);
      } else {
        isLoading.value = false;
        Get.snackbar(
          "Failed",
          "User login failed, please try again.",
          icon: const Icon(Icons.error, size: 40.0, color: Colors.blue),
          snackPosition: SnackPosition.TOP,
          duration: const Duration(milliseconds: 800),
          backgroundColor: Colors.yellow,
          //icon:Image(image:AssetImage("assets/images/dora.png"))
        );
      }
    });
  }

  void changePassword(
      String oldpassword, String newpassword, BuildContext context) {
    String token = currentUser[0]['token'];
    ////print("------- change password ######## ${currentUser[0]['token']} ###### --------");
    AuthService.changePassword(oldpassword, newpassword, token).then((value) {
      ////print("------- change password ######## $value ###### --------");
      if (value.isNotEmpty) {
        isLoading.value = false;
        Navigator.pop(context);
        if (rogMode.value == 1) {
          switchPage(AppPages.TRAVEL);
        } else {
          switchPage(AppPages.INDEX);
        }
      } else {
        Get.snackbar(
          'failed'.tr,
          'password_change_failed_please_try_again'.tr,
          icon: const Icon(Icons.error, size: 40.0, color: Colors.blue),
          snackPosition: SnackPosition.TOP,
          duration: const Duration(milliseconds: 800),
          backgroundColor: Colors.yellow,
          //icon:Image(image:AssetImage("assets/images/dora.png"))
        );
      }
    });
    isLoading.value = false;
  }

  void logout() async {
    locations.clear();
    DatabaseHelper db = DatabaseHelper.instance;
    db.deleteAllDestinations().then((value) {
      DestinationController destinationController =
          Get.find<DestinationController>();
      destinationController.populateDestinations();
    });
    currentUser.clear();
    cats.clear();
  }

  void register(String email, String password, BuildContext context) {
    AuthService.register(email, password).then((value) {
      if (value.isNotEmpty) {
        currentUser.clear();
        currentUser.add(value);
        isLoading.value = false;
        Navigator.pop(context);
        Get.toNamed(AppPages.INDEX);
      } else {
        isLoading.value = false;
        Get.snackbar(
          'failed'.tr,
          'user_registration_failed_please_try_again'.tr,
          icon: const Icon(Icons.error, size: 40.0, color: Colors.blue),
          snackPosition: SnackPosition.TOP,
          duration: const Duration(milliseconds: 800),
          backgroundColor: Colors.yellow,
          //icon:Image(image:AssetImage("assets/images/dora.png"))
        );
      }
    });
  }

  void saveToDevice(String val) async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setString("user_token", val);
  }

  void changeUser(Map<String, dynamic> value, {bool replace = true}) {
    //print("---- change user to $value -----");
    currentUser.clear();
    currentUser.add(value);
    if (replace) {
      saveToDevice(currentUser[0]["token"]);
    }
    isLoading.value = false;
    loadLocationsBound();
    if (currentUser.isNotEmpty) {
      rogMode.value = 0;
    } else {
      rogMode.value = 1;
    }
    //print('--- c rog mode --- ${rogMode.value}');
    Get.toNamed(AppPages.INDEX);
  }

  loadUserDetailsForToken(String token) async {
    AuthService.userForToken(token).then((value) {
      ////print("----token val-- $value  ------");
      if (value![0]["user"].isEmpty) {
        Get.toNamed(AppPages.LOGIN);
        return;
      }
      changeUser(value[0], replace: false);
    });
  }

  void loadLocationsBound() {
    if (isCustomAreaSelected.value == true) {
      return;
    }
    locations.clear();
    String cat = currentCat.isNotEmpty ? currentCat[0] : "";
    if (currentCat.isNotEmpty && currentCat[0] == "-all-") {
      cat = "";
    }
    LatLngBounds bounds = mapController.bounds!;
    currentBound.clear();
    currentBound.add(bounds);
    ////print(currentCat);
    LocationService.loadLocationsBound(
            bounds.southWest.latitude,
            bounds.southWest.longitude,
            bounds.northWest.latitude,
            bounds.northWest.longitude,
            bounds.northEast.latitude,
            bounds.northEast.longitude,
            bounds.southEast.latitude,
            bounds.southEast.longitude,
            cat)
        .then((value) {
      ////print("---value length ------ ${value!.collection.length}");
      if (value == null) {
        return;
      }
      if (value.collection.isEmpty) {
        if (showPopup == false) {
          return;
        }
        Get.snackbar(
          "Too many Points",
          "please zoom in",
          icon: const Icon(Icons.assistant_photo_outlined,
              size: 40.0, color: Colors.blue),
          snackPosition: SnackPosition.TOP,
          duration: const Duration(milliseconds: 800),
          backgroundColor: Colors.yellow,
          //icon:Image(image:AssetImage("assets/images/dora.png"))
        );
        showPopup = false;
        //Get.showSnackbar(GetSnackBar(message: "Too many points, please zoom in",));
      }
      if (value.collection.isNotEmpty) {
        ////print("---- added---");
        locations.add(value);
      }
    });
  }

  void setBound(LatLngBounds bounds) {
    currentBound.clear();
    currentBound.add(bounds);
  }

  GeoJsonFeature? getFeatureForLatLong(double lat, double long) {
    if (locations.isNotEmpty) {
      for (GeoJsonFeature i in locations[0].collection) {
        GeoJsonMultiPoint p = i.geometry as GeoJsonMultiPoint;
        if (p.geoSerie!.geoPoints[0].latitude == lat &&
            p.geoSerie!.geoPoints[0].longitude == long) {
          return i;
        }
      }
    }
    return null;
  }
}
