// ignore_for_file: avoid_print

import 'package:dio/dio.dart';
import 'package:english_learning/core/services/constants.dart';

class DioClient {
  final Dio _dio = Dio();

  DioClient() {
    _dio.options.baseUrl = baseUrl;
    _dio.options.connectTimeout = const Duration(seconds: 5);
    _dio.options.receiveTimeout = const Duration(seconds: 10);
  }

  Future<Response> refreshAccessToken(String refreshToken) async {
    try {
      final response = await _dio.post(
        '/api/refreshToken',
        data: {'REFRESH_TOKEN': refreshToken},
        options: Options(
          headers: {
            'Content-Type': 'application/json',
          },
        ),
      );
      return response;
    } catch (e) {
      print('Refresh Token error: $e');
      rethrow;
    }
  }

  Future<Response> post(String path, {dynamic data, Options? options}) async {
    try {
      final response = await _dio.post(
        path,
        data: data,
        options:
            options ?? Options(headers: {'Content-Type': 'application/json'}),
      );
      return response;
    } on DioException catch (e) {
      print('DioError: ${e.response?.data ?? e.message}');
      rethrow;
    } catch (e) {
      print('Unexpected error: $e');
      rethrow;
    }
  }

  Future<Response> updateUserProfile(
      String id, FormData formData, String token) async {
    try {
      final response = await _dio.put(
        '/api/user/update/$id',
        data: formData,
        options: Options(
          headers: {
            'Authorization': 'Bearer $token',
            'Content-Type': 'multipart/form-data',
          },
        ),
      );
      return response;
    } catch (e) {
      print('Update Profile error: $e');
      rethrow;
    }
  }

  Future<Response> updatePassword(
    String id,
    Map<String, dynamic> data,
    String token,
  ) async {
    try {
      final response = await _dio.put(
        '/api/user/update/password/$id',
        data: data,
        options: Options(
          headers: {
            'Authorization': 'Bearer $token',
            'Content-Type': 'application/json',
          },
        ),
      );
      return response;
    } catch (e) {
      print('Update Password error: $e');
      rethrow;
    }
  }

  Future<Response> reportIssue(
    Map<String, dynamic> data,
    String token,
  ) async {
    try {
      final response = await _dio.post(
        '/api/report',
        data: data,
        options: Options(
          headers: {
            'Authorization': 'Bearer $token',
            'Content-Type': 'application/json',
          },
        ),
      );
      return response;
    } catch (e) {
      print('Update Password error: $e');
      rethrow;
    }
  }

  Future<Response> registerStudent(Map<String, dynamic> data) async {
    try {
      // Send POST request to the registration endpoint
      final response = await _dio.post(
        '/api/register/student',
        data: data,
        options: Options(
          headers: {
            'Content-Type': 'application/json',
          },
        ),
      );
      return response;
    } catch (e) {
      // Handle the error
      rethrow;
    }
  }

  Future<Response> loginStudent(Map<String, dynamic> data) async {
    try {
      final response = await _dio.post(
        '/api/login',
        data: data,
        options: Options(
          headers: {
            'Content-Type': 'application/json',
          },
        ),
      );
      return response;
    } catch (e) {
      rethrow;
    }
  }

  Future<Response> forgotPassword(Map<String, dynamic> data) async {
    try {
      final response = await _dio.post(
        '/api/forgotPassword',
        data: data,
        options: Options(
          headers: {
            'Content-Type': 'application/json',
          },
        ),
      );
      return response;
    } catch (e) {
      rethrow;
    }
  }

  Future<Response> getMe(String token) async {
    try {
      print('Sending getMe request with token: Bearer $token');
      final response = await _dio.get(
        '/api/getMe',
        options: Options(
          headers: {
            'Authorization': 'Bearer $token', // Add 'Bearer ' prefix here
          },
        ),
      );
      print('getMe response: ${response.data}');
      return response;
    } catch (e) {
      print('GetMe error: $e');
      rethrow;
    }
  }

  Future<Response> getSections(String token) async {
    try {
      final response = await _dio.get(
        '/api/section',
        options: Options(
          headers: {
            'Authorization': 'Bearer $token',
            'Content-Type': 'application/json',
          },
        ),
      );
      print('getSections response: ${response.data}');
      return response;
    } catch (e) {
      print('GetSections error: $e');
      rethrow;
    }
  }

  Future<Response> getTopics(String sectionId, String token) async {
    try {
      final response = await _dio.get(
        '/api/topic/section/$sectionId',
        options: Options(
          headers: {
            'Authorization': 'Bearer $token',
            'Content-Type': 'application/json',
          },
        ),
      );
      print('getTopics response: ${response.data}');
      return response;
    } catch (e) {
      print('GetTopics error: $e');
      rethrow;
    }
  }

  Future<Response> getLevels(String topicsId, String token) async {
    try {
      final response = await _dio.get(
        '/api/level/topic/$topicsId',
        options: Options(
          headers: {
            'Authorization': 'Bearer $token',
            'Content-Type': 'application/json',
          },
        ),
      );
      print('getLevels response: ${response.data}');
      return response;
    } catch (e) {
      print('GetLevels error: $e');
      rethrow;
    }
  }

  Future<Response> createStudentLearning(String idLevel, String token) async {
    try {
      final response = await _dio.post(
        '/api/stdLearning',
        data: {'ID_LEVEL': idLevel},
        options: Options(
          headers: {
            'Authorization': 'Bearer $token',
            'Content-Type': 'application/json',
          },
        ),
      );
      return response;
    } catch (e) {
      print('Create Student Learning error: $e');
      rethrow;
    }
  }

  Future<Response> getExercises(String levelId, String token) async {
    try {
      final response = await _dio.get(
        '/api/exercise/level/$levelId',
        options: Options(
          headers: {
            'Authorization': 'Bearer $token',
            'Content-Type': 'application/json',
          },
        ),
      );
      print('getExercises response: ${response.data}');
      return response;
    } on DioException catch (e) {
      print(
          'DioError: ${e.response?.statusCode} - ${e.response?.data ?? e.message}');
      rethrow;
    } catch (e) {
      print('Unexpected error: $e');
      rethrow;
    }
  }

  Future<Response> submitExerciseAnswers(
      List<Map<String, dynamic>> answers, String token) async {
    try {
      final response = await _dio.post(
        '/api/stdExercise',
        data: {'answers': answers},
        options: Options(
          headers: {
            'Authorization': 'Bearer $token',
            'Content-Type': 'application/json',
          },
        ),
      );
      print('submitExerciseAnswers response: ${response.data}');
      return response;
    } catch (e) {
      print('SubmitExerciseAnswers error: $e');
      rethrow;
    }
  }

  Future<Response> getScore(String stdLearningId, String token) async {
    try {
      final response = await _dio.get(
        '/api/stdLearning/score/$stdLearningId',
        options: Options(
          headers: {
            'Authorization': 'Bearer $token',
            'Content-Type': 'application/json',
          },
        ),
      );
      print('getScore response: ${response.data}');
      return response;
    } catch (e) {
      print('GetScore error: $e');
      rethrow;
    }
  }

  Future<Response> getLearningHistory(
    String sectionId,
    String token, {
    int page = 1,
    int limit = 5,
  }) async {
    try {
      final response = await _dio.get(
        '/api/learningHistory/section/$sectionId',
        queryParameters: {
          'page': page,
          'limit': limit,
        },
        options: Options(
          headers: {
            'Authorization': 'Bearer $token',
            'Content-Type': 'application/json',
          },
        ),
      );
      print('getLearningHistory response: ${response.data}');
      return response;
    } catch (e) {
      print('GetLearningHistory error: $e');
      rethrow;
    }
  }

  Future<Response> getCompletedTopics(String token) async {
    try {
      final response = await _dio.get(
        '/api/topic/complete',
        options: Options(
          headers: {
            'Authorization': 'Bearer $token',
            'Content-Type': 'application/json',
          },
        ),
      );
      print('getCompletedTopics response: ${response.data}');
      return response;
    } catch (e) {
      print('GetCompletedTopics error: $e');
      rethrow;
    }
  }

  Future<Response> studentFeedback(
    String stdLearningId,
    String feedback,
    String token,
  ) async {
    try {
      final response = await _dio.put(
        '/api/stdLearning/$stdLearningId',
        data: {'FEEDBACK_STUDENT': feedback},
        options: Options(
          headers: {
            'Authorization': 'Bearer $token',
            'Content-Type': 'application/json',
          },
        ),
      );
      return response;
    } catch (e) {
      print('Submit Feedback error: $e');
      rethrow;
    }
  }

  Future<Response> getStudentAnswers(String stdLearningId, String token) async {
    try {
      final response = await _dio.get(
        '/api/studentAnswers/$stdLearningId',
        options: Options(
          headers: {
            'Authorization': 'Bearer $token',
            'Content-Type': 'application/json',
          },
        ),
      );
      print('studentAnswers response: ${response.data}');
      return response;
    } catch (e) {
      print('StudentAnswers error: $e');
      rethrow;
    }
  }
}
