import 'package:get/get.dart';

import 'package:f0ckapp/controller/authcontroller.dart';
import 'package:f0ckapp/models/item.dart';
import 'package:f0ckapp/models/feed.dart';

class ApiService extends GetConnect {
  final AuthController _authController = Get.find<AuthController>();

  Future<Feed> fetchItems({
    int? older,
    int? newer,
    int type = 0,
    int mode = 0,
    int random = 0,
    String? tag,
  }) async {
    String? token = _authController.token.value;
    final params = <String, String>{
      'type': type.toString(),
      'mode': mode.toString(),
      'random': random.toString(),
    };
    if (older != null) params['older'] = older.toString();
    if (newer != null) params['newer'] = newer.toString();
    if (tag != null) params['tag'] = tag;

    final Map<String, String> headers = <String, String>{};
    if (token != null && token.isNotEmpty) {
      headers['Authorization'] = 'Bearer $token';
    }

    final Response<dynamic> response = await get(
      'https://api.f0ck.me/items_new/get',
      query: params,
      headers: headers,
    );

    if (response.status.code == 200 && response.body is Map<String, dynamic>) {
      final Feed feed = Feed.fromJson(response.body as Map<String, dynamic>);
      feed.items.sort((a, b) => b.id.compareTo(a.id));
      return feed;
    } else {
      if (!Get.isSnackbarOpen) {
        Get.snackbar('Fehler', 'Fehler beim Laden der Items');
      }
      throw Exception('Fehler beim Laden der Items');
    }
  }

  Future<MediaItem> fetchItemById(int itemId) async {
    String? token = _authController.token.value;
    final Map<String, String> headers = <String, String>{};
    if (token != null && token.isNotEmpty) {
      headers['Authorization'] = 'Bearer $token';
    }

    final Response<dynamic> response = await get(
      'https://api.f0ck.me/item/$itemId',
      headers: headers,
    );

    if (response.status.code == 200 && response.body is Map<String, dynamic>) {
      return MediaItem.fromJson(response.body as Map<String, dynamic>);
    } else {
      if (!Get.isSnackbarOpen) {
        Get.snackbar('Fehler', 'Fehler beim Laden des Items');
      }
      throw Exception('Fehler beim Laden des Items');
    }
  }

  Future<List<Favorite>?> toggleFavorite(
    MediaItem item,
    bool isFavorite,
  ) async {
    String? token = _authController.token.value;
    if (token == null || token.isEmpty) return null;

    final Map<String, String> headers = {
      'Authorization': 'Bearer $token',
      'Content-Type': 'application/json',
    };

    try {
      Response response;
      if (!isFavorite) {
        response = await put(
          'https://api.f0ck.me/favorites/${item.id}',
          null,
          headers: headers,
        );
      } else {
        response = await delete(
          'https://api.f0ck.me/favorites/${item.id}',
          headers: headers,
        );
      }
      if (response.status.code == 200 && response.body is List) {
        return (response.body as List)
            .map((json) => Favorite.fromJson(json))
            .toList();
      } else {
        return null;
      }
    } catch (e) {
      return null;
    }
  }
}
