import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:pretty_dio_logger/pretty_dio_logger.dart';

final ApiService apiService = ApiService();

class ApiService {
  final baseUrl = 'https://lba-api.liara.run';

  late Dio _dio;

  void setAuthToken(String token) {
    _dio.options.headers['Authorization'] = 'Bearer $token';
  }

  ApiService() {
    _dio = Dio(
      BaseOptions(
        baseUrl: baseUrl, // 🔹 Set your API base URL
        connectTimeout: const Duration(seconds: 10), // Timeout settings
        receiveTimeout: const Duration(seconds: 10),
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json',
        },
      ),
    )..interceptors.add(PrettyDioLogger(
        enabled: kDebugMode,
      ));
    setAuthToken(
        'eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJheC1zX3N3Tm5fU1hDTVkzWFowSDVKekNhQ0psVXh6bmZ0WHBxSk1YUEF3In0.eyJleHAiOjE3NDAyMzg4NzQsImlhdCI6MTc0MDIwMjg3NCwianRpIjoiYjljZTBkZDUtMGJmMy00YWIyLWIxODktNTQyNmZjZWFkODc0IiwiaXNzIjoiaHR0cHM6Ly9rZXljbG9hay5saWFyYS5ydW4vcmVhbG1zL2xiYSIsImF1ZCI6ImFjY291bnQiLCJzdWIiOiJmMzljODIxNi0zODhhLTQ0ZTEtODVhOC00Zjk5NmU2NmU2MDQiLCJ0eXAiOiJCZWFyZXIiLCJhenAiOiJmcm9udGVuZCIsInNpZCI6IjA5NGNjNmI5LWUwYWMtNDk5Zi04ZGYyLTA5NjkyY2M4YTFiMiIsImFjciI6IjEiLCJhbGxvd2VkLW9yaWdpbnMiOlsiaHR0cHM6Ly9sYmEtYXBpLmxpYXJhLnJ1bi8qIiwiaHR0cDovL2xvY2FsaG9zdDozMDAwLyoiLCIvKiJdLCJyZWFsbV9hY2Nlc3MiOnsicm9sZXMiOlsiZGVmYXVsdC1yb2xlcy1sYmEiLCJvZmZsaW5lX2FjY2VzcyIsInVtYV9hdXRob3JpemF0aW9uIl19LCJyZXNvdXJjZV9hY2Nlc3MiOnsiYWNjb3VudCI6eyJyb2xlcyI6WyJtYW5hZ2UtYWNjb3VudCIsIm1hbmFnZS1hY2NvdW50LWxpbmtzIiwidmlldy1wcm9maWxlIl19LCJmcm9udGVuZCI6eyJyb2xlcyI6WyJzaG9wIiwidXNlciJdfX0sInNjb3BlIjoib3BlbmlkIGVtYWlsIHByb2ZpbGUiLCJlbWFpbF92ZXJpZmllZCI6dHJ1ZSwibmFtZSI6ImRlbW8gZGVtbyIsInByZWZlcnJlZF91c2VybmFtZSI6ImRlbW8iLCJnaXZlbl9uYW1lIjoiZGVtbyIsImZhbWlseV9uYW1lIjoiZGVtbyIsImVtYWlsIjoiZGVtb0BnbWFpbC5jb20ifQ.Z25daqvbCQ-g2wp_geuKilZlx6YhBkJVs4IeS2P-R89WIuDcxu0BiJJkiqolO7H1iirEo_r2P3-RkrzDBRBRPFmLIlxJCR_D_sr7e6qanudqtVkRrSxQPykcRDlRqKZkfyB4pSe8nfimlpt0XCsiXSEC-rOUWVctOoibYWiCcRrMq9TD5SZ0HUuZoC0tiRAAQ1PtgwwHG0anqTbSdtHV9H1RpfhCuz34fbWFm8g9fOPM2wrVkhjnBg8wx0ein_NAj8vbj18NVzn46b9EoIS5r7njH7hPIjx-VWQ2fnlogzVw7Odv6cSf8IlEf93hxHBDYs9PsAu3oPsQ1HP_CGcR1g');
  }

  /// 🔹 Handle GET requests
  Future<dynamic> get(String endpoint, {Map<String, dynamic>? params}) async {
    try {
      Response response = await _dio.get(endpoint, queryParameters: params);
      return response.data;
    } catch (e) {
      _handleError(e);
    }
  }

  /// 🔹 Handle POST requests
  Future<dynamic> post(String endpoint, {dynamic data}) async {
    try {
      Response response = await _dio.post(endpoint, data: data);
      return response.data;
    } catch (e) {
      _handleError(e);
    }
  }

  /// 🔹 Handle PUT requests
  Future<dynamic> put(String endpoint, {dynamic data}) async {
    try {
      Response response = await _dio.put(endpoint, data: data);
      return response.data;
    } catch (e) {
      _handleError(e);
    }
  }

  /// 🔹 Handle DELETE requests
  Future<dynamic> delete(String endpoint, {dynamic data}) async {
    try {
      Response response = await _dio.delete(endpoint, data: data);
      return response.data;
    } catch (e) {
      _handleError(e);
    }
  }

  /// 🔹 Error handling
  void _handleError(dynamic error) {
    if (error is DioException) {
      switch (error.type) {
        case DioExceptionType.connectionTimeout:
          throw Exception("Connection timeout, please try again.");
        case DioExceptionType.receiveTimeout:
          throw Exception("Receive timeout, please try again.");
        case DioExceptionType.badResponse:
          throw Exception("Server error: ${error.response?.statusCode}");
        case DioExceptionType.cancel:
          throw Exception("Request canceled.");
        default:
          throw Exception("Unexpected error occurred.");
      }
    } else {
      throw Exception("Unknown error: $error");
    }
  }
}
