import 'dart:convert';

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

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

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

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

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

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

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: PopAppbar(
          onPressed: () {
            Navigator.pop(context);
          },
          label: 'Tu ubicación'),
      body: Center(
        child: Container(
          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]['description']);
                      },
                      title: Text(_placesList[index]['description']),
                    );
                  },
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
