import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:http/http.dart';
import 'package:sendtrain/models/google_place_model.dart';
import 'package:sendtrain/widgets/generic/elements/form_search_input.dart';
import 'package:uuid/uuid.dart';

class GooglePlacesService {
  final sessionToken = Uuid().v4();
  final apiKey = "AIzaSyBCjMCEAyyNVpsnVYvZj6VL1mmB98Vd6AE";
  final client = Client();

  void finish() {
    client.close();
  }

  Future<List<Suggestion>?> fetchSuggestions(String input) async {
    var headers = {
      'Content-Type': 'application/json',
      'X-Goog-Api-Key': apiKey,
      "Access-Control-Allow-Origin": "*",
      'X-Goog-FieldMask':
          'places.displayName,places.id,places.formattedAddress,places.photos'
    };
    var request = Request('POST',
        Uri.parse('https://places.googleapis.com/v1/places:searchText'));
    request.body = json.encode({"textQuery": input});
    request.headers.addAll(headers);

    StreamedResponse response = await request.send();

    if (response.statusCode == 200) {
      final result = json.decode(await response.stream.bytesToString());

      if (result.isNotEmpty) {
        return result['places']
            .map<Suggestion>((p) => Suggestion<GooglePlaceModel>(
                GooglePlaceModel(
                    placeId: p['id'],
                    description: p['displayName']['text'],
                    address: p['formattedAddress'],
                    imageReferences: p['photos'])))
            .toList();
      } else {
        return null;
      }
    } else {
      throw Exception(response.reasonPhrase);
    }
  }

  Future fetchPhoto(String name) async {
    var headers = {
      "Access-Control-Allow-Origin": "*",
    };

    var request = Request(
        'GET',
        Uri.parse(
            'https://places.googleapis.com/v1/$name/media?key=$apiKey&maxWidthPx=800&skipHttpRedirect=true'));
    request.headers.addAll(headers);

    StreamedResponse response = await request.send();

    if (response.statusCode == 200) {
      final result = json.decode(await response.stream.bytesToString());

      if (result.isNotEmpty) {
        return result;
      } else {
        return null;
      }
    } else {
      throw Exception(response.reasonPhrase);
    }
  }

  Widget resultWidget(GooglePlaceModel place, Function? callback) {
    return ListTile(
      title: Text(place.description),
      onTap: () async {
        if (callback != null) {
          callback();
        }
      },
    );
  }
}
