import 'dart:async';

import 'package:yandex_mapkit/yandex_mapkit.dart';

class GeocodingRemoteDataSource {

  Future<String> getAddressFromPoint({
    required double latitude,
    required double longitude,
  }) async {
    final point = Point(
      latitude: latitude,
      longitude: longitude,
    );

    final (session, resultFuture) = await YandexSearch.searchByPoint(
      point: point,
      zoom: 16,
      searchOptions: const SearchOptions(
        searchType: SearchType.geo,
        resultPageSize: 1,
      ),
    );

    try {
      final result = await resultFuture;

      if (result.items == null || result.items!.isEmpty) {
        throw Exception("Адрес не найден");
      }

      final item = result.items!.first;

      print("ADDRESS FETCH RESULT ${item.name}");

      final toponymAddress =
          item.toponymMetadata?.address?.formattedAddress;

      if (toponymAddress != null && toponymAddress.isNotEmpty) {
        return toponymAddress;
      }

      final businessAddress =
          item.businessMetadata?.address?.formattedAddress;

      if (businessAddress != null && businessAddress.isNotEmpty) {
        return businessAddress;
      }

      return item.name;
    } catch (e) {
      throw Exception("Ошибка получения адреса: $e");
    } finally {
      await session.close();
    }
  }

  Future<List<MasstransitRoute>?> getPedestrianRoutes(
      Point userPosition,
      Point targetPosition,
      ) async {
    try {

      print("From: ${userPosition.latitude}, ${userPosition.longitude}");
      print("To: ${targetPosition.latitude}, ${targetPosition.longitude}");

      final (session, resultFuture) = await YandexPedestrian.requestRoutes(
          points: [
            RequestPoint(point: userPosition, requestPointType: RequestPointType.wayPoint),
            RequestPoint(point: targetPosition, requestPointType: RequestPointType.wayPoint)
          ],
          fitnessOptions: const FitnessOptions(avoidSteep: false, avoidStairs: false),
          timeOptions: const TimeOptions()
      );

      final result = await resultFuture;

      if (result.routes == null || result.routes!.isEmpty) {
        print("Маршруты не найдены: список пуст или null");
        return [];
      }

      final route = result.routes!.first;

      final distance = route.metadata.weight.walkingDistance?.value;

      if (distance != null) {
        print("Дистанция до самоката: $distance м");
      } else {
        print("Дистанция не найдена в метаданных маршрута");
      }

      return result.routes;

    } catch (e, stack) {
      print('Pedestrian route error: $e');
      print('Stack trace: $stack');
      return null;
    }
  }
}