import 'dart:io';
import 'package:path_provider/path_provider.dart';
import 'package:dio/dio.dart';
import 'package:qadirneyriz/config/config.dart';
import 'package:qadirneyriz/setting/setting.dart';
import 'package:qadirneyriz/utils/result/result.dart';

class ReportApi {
  Future<Result?> downloadReportMeetings(
      {String? fromDate,
      String? toDate,
      int? location,
      int? subject,
      int? meetingManager,
      int? status,
      required String format}) async {
    try {
      final Map<String, String> headers = {"Accept": "application/json"};
      String dataToken = setting.userLocalDb.getUser().token!;
      if (dataToken != '') {
        headers['Authorization'] = "Bearer $dataToken";
      }
      final Directory tempDir = await getApplicationDocumentsDirectory();

      final String tempPath = tempDir.path;
      final String savePath = '$tempPath/report.$format';

      final res = await Dio().download(
        '${config.network.baseUrl}statistic',
        savePath,
        queryParameters: {
          'date_meeting_az': fromDate,
          'date_meeting_ta': toDate,
          'location': location,
          'subject': subject,
          'meeting_manager': meetingManager,
          'status': status,
          'format': format
        },
        options: Options(headers: headers),
      );

      if (res.statusCode == 200 || res.statusCode == 201) {
        return Result(isOk: true, message: savePath);
      } else {
        return Result(
            isOk: false, message: 'Failed with status code: ${res.statusCode}');
      }
    } on DioException catch (e) {
      // print(e);
      return Result(
        isOk: false,
        errors: e.response?.data['errors'],
        message:
            e.response?.data['message'] ?? 'An error occurred during download.',
      );
    }
  }

  Future<Result?> downloadReportPrivateMeetings(
      {String? fromDate,
      String? toDate,
      int? location,
      int? subject,
      int? meetingManager,
      int? status,
      required String format}) async {
    try {
      final Map<String, String> headers = {"Accept": "application/json"};
      String dataToken = setting.userLocalDb.getUser().token!;
      if (dataToken != '') {
        headers['Authorization'] = "Bearer $dataToken";
      }

      final Directory tempDir = await getApplicationDocumentsDirectory();
      final String tempPath = tempDir.path;
      final String savePath = '$tempPath/reportprivatemeeting.$format';

      // print("Download path: $savePath");

      final String url = '${config.network.baseUrl}private_meetings/export';
      // print("Download URL: $url");

      final Map<String, dynamic> params = {
        'date_meeting_az': fromDate,
        'date_meeting_ta': toDate,
        'location': location,
        'subject': subject,
        'meeting_manager': meetingManager,
        'status': status,
        'format': format
      };

      // print("Request parameters: $params");

      final res = await Dio().download(
        url,
        savePath,
        queryParameters: params,
        options: Options(headers: headers),
      );

      // print("Response status: ${res.statusCode}");
      // print("Response headers: ${res.headers}");

      if (res.statusCode == 200 || res.statusCode == 201) {
        // print("File downloaded successfully: $savePath");
        return Result(isOk: true, message: savePath);
      } else {
        print("Failed with status code: ${res.statusCode}");
        return Result(
            isOk: false, message: 'Failed with status code: ${res.statusCode}');
      }
    } on DioException catch (e) {
      print("DioException: $e");
      print("Error response data: ${e.response?.data}");

      return Result(
        isOk: false,
        errors: e.response?.data['errors'],
        message:
            e.response?.data['message'] ?? 'An error occurred during download.',
      );
    }
  }
}
