import 'package:flutter/material.dart';
import 'package:latlong2/latlong.dart';
import 'package:osm_nominatim/osm_nominatim.dart';

class LocationSearchDelegate extends SearchDelegate<LatLng?> {
  @override
  List<Widget>? buildActions(BuildContext context) {
    return [
      IconButton(
        icon: const Icon(Icons.clear),
        onPressed: () => query = '',
      )
    ];
  }

  @override
  Widget? buildLeading(BuildContext context) {
    return IconButton(
      icon: const Icon(Icons.arrow_back),
      onPressed: () => close(context, null),
    );
  }

  @override
  Widget buildResults(BuildContext context) {
    return FutureBuilder<List<Place>>(
      future: query.isEmpty ? Future.value([]) : Nominatim.searchByName(
          query: query,
          limit: 10,
          language: 'de',
          // https://gist.github.com/graydon/11198540#file-country-bounding-boxes-py-L45
          viewBox: ViewBox(54.983104153, 15.0169958839, 47.3024876979, 5.98865807458)
      ),
      builder: (BuildContext context, AsyncSnapshot<List<Place>> snapshot) {
        switch (snapshot.connectionState) {
          case ConnectionState.waiting:
            return const Center(child: CircularProgressIndicator());
          case ConnectionState.active:
          case ConnectionState.none:
          case ConnectionState.done:
            if ((snapshot.data?.length ?? 0) == 0) {
              return const Row(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  SizedBox(height: 50),
                  Text("Keine Sucherergebnisse gefunden")
                ],
              );
            }
            return ListView.builder(
              itemCount: snapshot.data!.length,
              itemBuilder: (context, index) {
                Place place = snapshot.data![index];
                return ListTile(
                  title: Text(place.displayName),
                  onTap: () => close(context, LatLng(place.lat, place.lon)),
                );
              },
            );
        }
      },
    );
  }

  @override
  Widget buildSuggestions(BuildContext context) {
    return buildResults(context);
  }
}
