import "dart:async";

import "package:client/data.dart";
import "package:client/services.dart";
import "package:flutter/widgets.dart" hide Path;

import "package:google_maps_flutter/google_maps_flutter.dart";

import "home_markers.dart";
import "view_model.dart";

/// The view model for the home page.
class HomeModel extends ViewModel with HomeMarkers {
  final startLatitudeController = TextEditingController();
  final startLongitudeController = TextEditingController();
  final endLatitudeController = TextEditingController();
  final endLongitudeController = TextEditingController();

  Path? path;
  GoogleMapController? mapController;

  double? get startLatitude => double.tryParse(startLatitudeController.text);
  double? get startLongitude => double.tryParse(startLongitudeController.text);
  double? get endLatitude => double.tryParse(endLatitudeController.text);
  double? get endLongitude => double.tryParse(endLongitudeController.text);

  bool isSearching = false;
  bool isGoogleReady = false;
  List<List<LatLng>> routes = [];

  @override
  Future<void> init() async {
    await Future<void>.delayed(const Duration(seconds: 2));
    isGoogleReady = true;
    notifyListeners();
    await updateMarkers();
  }

  void onMapTapped(LatLng coordinates) {
    if (!shouldShowMarkers) return;
    final marker = Marker(
      markerId: markerId,
      position: coordinates,
      icon: markerIcon,
      infoWindow: InfoWindow(title: "$startOrEnd here"),
    );
    switch (markerState!) {
      case MarkerState.start: updateStart(coordinates, marker);
      case MarkerState.end: updateEnd(coordinates, marker);
    }
  }

  @override
  void updateStart(LatLng coordinates, Marker marker) {
    startLatitudeController.text = coordinates.latitude.toString();
    startLongitudeController.text = coordinates.longitude.toString();
    super.updateStart(coordinates, marker);
  }

  @override
  void updateEnd(LatLng coordinates, Marker marker) {
    endLatitudeController.text = coordinates.latitude.toString();
    endLongitudeController.text = coordinates.longitude.toString();
    super.updateEnd(coordinates, marker);
  }

  String? pathText;
  Future<void> search() async {
    final start = (lat: startLatitude, long: startLongitude);
    final end = (lat: endLatitude, long: endLongitude);
    if (start.lat == null || start.long == null) return;
    if (end.lat == null || end.long == null) return;
    isSearching = true;
    isLoading = true;
    final result = await services.api.getPath2(start: start as Coordinates, end: end as Coordinates);
    pathText = result ?? "An error occurred";
    // path = result;
    isLoading = false;
    if (result == null) return;
    isSearching = false;
    // routes = [
    //   for (final step in result) [
    //     ...decodePolyline(step.trip.polyline),
    //   ],
    // ];
    notifyListeners();
  }
}
