import 'package:flutter/material.dart';
import 'package:geojson/geojson.dart';
import 'package:get/get.dart';
import 'package:rogapp/model/destination.dart';
import 'package:rogapp/pages/destination/destination_controller.dart';
import 'package:rogapp/pages/index/index_controller.dart';
import 'package:rogapp/services/maxtrix_service.dart';
import 'package:rogapp/utils/const.dart';
import 'package:rogapp/widgets/bottom_sheet_new.dart';

class ListWidget extends StatefulWidget {
  const ListWidget({ Key? key }) : super(key: key);

  @override
  State<ListWidget> createState() => _ListWidgetState();
}

class _ListWidgetState extends State<ListWidget> {
  final IndexController indexController = Get.find<IndexController>();

  final DestinationController destinationController = Get.find<DestinationController>();

  Image getImage(int index){
    if(indexController.locations[0].collection[index].properties!["photos"] == null || indexController.locations[0].collection[index].properties!["photos"] == ""){
      return const Image(image: AssetImage('assets/images/empty_image.png'));
    }
    else{
      print("==== photo index is $index ===");
      String serverUrl = ConstValues.currentServer();
      GeoJsonFeature<dynamic> gf = indexController.locations[0].collection[index];
      String _photo = gf.properties!["photos"];
      return Image(
        image: NetworkImage(
          '$serverUrl/media/compressed/' + _photo
          ),
        errorBuilder: (BuildContext context, Object exception, StackTrace? stackTrace) {
          return Image.asset("assets/images/empty_image.png");
        },
        );
    }
  }

  void changeCurrentFeature(GeoJsonFeature fs){
    if(indexController.currentFeature.isNotEmpty){
      indexController.currentFeature.clear();
    }
    indexController.currentFeature.add(fs);
  }

  @override
  void initState() {
    super.initState();
  }

  Destination createDestination(GeoJsonFeature feature) {
    final props = feature.properties;
    GeoJsonMultiPoint _pt = feature.geometry;

    return Destination(
      cp: props!['cp'],
      lat: _pt.geoSerie!.geoPoints.first.latitude,
      lon: _pt.geoSerie!.geoPoints.first.longitude,
    );
  }

  Future<String> matrixDistance(int i) async {
    // Create two destinations directly from indexController.locations[0].collection
    Destination desCurr = Destination(lat: indexController.current_lat, lon: indexController.current_lon);
    //Destination dest1 = createDestination(indexController.locations[0].collection[0]);
    Destination dest2 = createDestination(indexController.locations[0].collection[i]);

    // Get the distance between these two destinations
    final res = await MatrixService.getDestinations([desCurr, dest2]);

    return res["routes"][0]["legs"][0]["distance"]["text"];
    //print("matrix result is ${i} : ${res["routes"][0]["legs"][0]["distance"]["text"]} ");
  }

  Future<void> _pullRefresh() async {
    print("pull to refesh");
    indexController.locations[0].collection.sort((a, b) => 
        (a.properties!['cp'] as Comparable)
        .compareTo(b.properties!['cp'] as Comparable));
    setState(() {
    });
  }

  @override
  Widget build(BuildContext context) {
    return Obx(() =>
              indexController.locations.isNotEmpty ?
              RefreshIndicator(
                onRefresh: _pullRefresh,
                child: ListView.builder(
                itemCount: indexController.locations[0].collection.length,
                shrinkWrap: true,
                itemBuilder: (_, index){
                  bool _is_found = false;
                  for(Destination d in destinationController.destinations){
                    if(indexController.locations[0].collection[index].properties!['location_id'] == d.location_id){
                      _is_found = true;
                      break;
                    }
                  }
                  return Card(
                    child: ListTile(
                      selected: _is_found,
                      
                      selectedTileColor: Colors.yellow.shade200,
                      onTap: (){
                        GeoJsonFeature gf = indexController.locations[0].collection[index];
                        changeCurrentFeature(gf);
                        showModalBottomSheet(
                            isScrollControlled: true,
                            context: context,
                            //builder: (context) => BottomSheetWidget(),
                            builder:((context) => BottomSheetNew())
                          );
                      },
                      leading: getImage(index),
                      title: indexController.locations[0].collection[index].properties!['location_name'] != null ? Text(indexController.locations[0].collection[index].properties!['location_name'].toString()) : const Text(""),
                      subtitle: indexController.locations[0].collection[index].properties!['category'] != null ? Text(indexController.locations[0].collection[index].properties!['category']) : const Text(""),
                      trailing: Column(
                        crossAxisAlignment: CrossAxisAlignment.end,
                        children: [
                          indexController.locations[0].collection[index].properties!['sub_loc_id'] != null ? Text(indexController.locations[0].collection[index].properties!['sub_loc_id']) : const Text(""),
                          SizedBox(
                            width: 100,
                            child: FutureBuilder<String>(
                              future: matrixDistance(index),
                              builder: (context, snapshot){
                                if(snapshot.connectionState == ConnectionState.waiting){
                                  return const Center(child: CircularProgressIndicator(),);
                                }
                                if(snapshot.hasError){
                                  return const Text("-");
                                }
                                else{
                                  return Text(snapshot.data ?? '', style: const TextStyle(color: Colors.red, fontWeight: FontWeight.bold),);
                                }
                              },
                            ),
                          )
                        ],
                      )
                    ),
                  );
                },
                          ),
              ) : const SizedBox(width: 0, height: 0,),
            );
  }
}