
// A search bar that allow the user to enter a city name
import 'package:anyway/structs/landmark.dart';
import 'package:geocoding/geocoding.dart';
import 'dart:developer';

import 'package:anyway/structs/trip.dart';
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
import 'package:shared_preferences/shared_preferences.dart';

const Map<String, List> debugLocations = {
  'paris': [48.8575, 2.3514],
  'london': [51.5074, -0.1278],
  'new york': [40.7128, -74.0060],
  'tokyo': [35.6895, 139.6917],
};



class NewTripLocationSearch extends StatefulWidget {
  Future<SharedPreferences> prefs = SharedPreferences.getInstance();
  Trip trip;

  NewTripLocationSearch(
    this.trip,
  );


  @override
  State<NewTripLocationSearch> createState() => _NewTripLocationSearchState();
}

class _NewTripLocationSearchState extends State<NewTripLocationSearch> {
  final TextEditingController _controller = TextEditingController();

  setTripLocation (String query) async {
    List<Location> locations = [];
    Location startLocation;
    log('Searching for: $query');
    if (GeocodingPlatform.instance != null) {
      locations.addAll(await locationFromAddress(query));
    }

    if (locations.isNotEmpty) {
      startLocation = locations.first;
    } else {
      log('No results found for: $query. Is geocoding available?');
      log('Setting Fallback location');
      List coordinates = debugLocations[query.toLowerCase()] ?? [48.8575, 2.3514];
      startLocation = Location(
        latitude: coordinates[0],
        longitude: coordinates[1],
        timestamp: DateTime.now(),
      );
    }

    widget.trip.landmarks.clear();
    widget.trip.addLandmark(
      Landmark(
        uuid: 'pending',
        name: query,
        location: [startLocation.latitude, startLocation.longitude],
        type: typeStart
      )
    );

  }

  late Widget locationSearchBar = SearchBar(
    hintText: 'Enter a city name or long press on the map.',
    onSubmitted: setTripLocation,
    controller: _controller,
    leading: const Icon(Icons.search),
    trailing: [
      ElevatedButton(
        onPressed: () {
          setTripLocation(_controller.text);
        },
        child: const Text('Search'),
      )
    ]
  );


  late Widget useCurrentLocationButton = ElevatedButton(
    onPressed: () async {
      // this widget is only shown if the user has already granted location permissions
      Position position = await Geolocator.getCurrentPosition();
      widget.trip.landmarks.clear();
      widget.trip.addLandmark(
        Landmark(
          uuid: 'pending',
          name: 'start',
          location: [position.latitude, position.longitude],
          type: typeStart
        )
      );
    },
    child: const Text('Use current location'),
  );

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: widget.prefs,
      builder: (context, snapshot) {
        if (snapshot.hasData) {
          final useLocation = snapshot.data!.getBool('useLocation') ?? false;
          if (useLocation) {
            return Column(
              children: [
                locationSearchBar,
                useCurrentLocationButton,
              ],
            );
          } else {
            return locationSearchBar;
          }
        } else {
          return locationSearchBar;
        }
      },
    );
  }
}
