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?> downloadReport(
      {String? fromDate,
      String? toDate,
      int? location,
      int? subject,
      int? meetingManager,
      int? status,
      String format = 'xlsx'}) 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,
        },
        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) {
      return Result(
        isOk: false,
        errors: e.response?.data['errors'],
        message:
            e.response?.data['message'] ?? 'An error occurred during download.',
      );
    }
  }
}
