import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:prosappco/src/components/network_utility.dart';
import 'package:prosappco/src/components/pop_appbar.dart';

import '../authentication/authentication_repository.dart';

class UbicacionScreen extends StatefulWidget {
  const UbicacionScreen({super.key});

  @override
  State<UbicacionScreen> createState() => _UbicacionScreenState();
}

class _UbicacionScreenState extends State<UbicacionScreen> {
  List<dynamic> _placesList = [];
  String selectedPlace = '';
  String _coordsOfCity = '0.0,0.0';

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

    final uid = AuthenticationRepository.instance.getCurrentUserUid();

    if (_coordsOfCity == '0.0,0.0') {
      AuthenticationRepository.instance
          .getCoordsOfCity(uid.toString())
          .then((String s) => setState(() {
                _coordsOfCity = s;
              }));
    }
  }

  void placeAutoComplete(String query) async {
    Uri uri = Uri.https("admin.prosapp.co", "/autocomplete", {
      "input": query,
      "location": _coordsOfCity,
    });

    String? response = await NetworkUtility.fetchUrl(uri);

    if (response != null) {
      setState(() {
        _placesList = jsonDecode(response.toString())['results'];
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: PopAppbar(
          onPressed: () {
            Navigator.pop(context);
          },
          label: 'Tu ubicación'),
      body: Center(
        child: SizedBox(
          width: 300,
          child: Column(
            children: [
              const SizedBox(height: 20.0),
              TextFormField(
                decoration: const InputDecoration(
                  hintText: 'Escribe tu ubicación',
                  prefixIcon: Icon(Icons.location_on),
                ),
                onChanged: (value) {
                  String modifiedValue = value.replaceAll(' ', '_');
                  placeAutoComplete(modifiedValue);
                },
              ),
              const SizedBox(height: 20.0),
              Expanded(
                child: ListView.builder(
                  itemCount: _placesList.length,
                  itemBuilder: (context, index) {
                    return ListTile(
                      onTap: () {
                        Navigator.pop(context, [
                          _placesList[index]['formatted_address'],
                          _placesList[index]['geometry']['location']['lat'],
                          _placesList[index]['geometry']['location']['lng']
                        ]);
                      },
                      title: Text(_placesList[index]['formatted_address']),
                    );
                  },
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
