import 'dart:io';
import 'package:dio/dio.dart';
import '../network/dio_client.dart';
import '../utils/logger.dart';

class InvoiceUploadService {
  final Dio _dio = DioClient().client;

  /// Uploads a batch of images to the server
  /// Returns the batchId if successful, null otherwise.
  Future<String?> uploadBatch({
    required String companyId,
    required List<File> images,
    required Function(int current, int total) onProgress,
  }) async {
    try {
      // 1. Create Batch
      AppLogger.print('Creating new batch for company: $companyId');
      final createResponse = await _dio.post('batches/create', data: {
        'company_id': companyId,
        'total_images': images.length,
      });

      if (createResponse.statusCode != 200 && createResponse.statusCode != 201) {
        throw Exception('Failed to create batch');
      }

      final String batchId = createResponse.data['data']['batch_id'];
      AppLogger.print('Batch created successfully: $batchId');

      // 2. Upload Images sequentially
      for (int i = 0; i < images.length; i++) {
        final file = images[i];
        final fileName = file.path.split('/').last;

        FormData formData = FormData.fromMap({
          'batch_id': batchId,
          'image': await MultipartFile.fromFile(file.path, filename: fileName),
          'order_index': i + 1,
        });

        AppLogger.print('Uploading image ${i + 1}/${images.length}: $fileName');
        
        await _dio.post(
          'batches/upload-image',
          data: formData,
          onSendProgress: (int sent, int total) {
            // Can be used for detailed progress bar per image if needed
          },
        );

        onProgress(i + 1, images.length);
      }

      // 3. Finalize Batch
      AppLogger.print('Finalizing batch: $batchId');
      final finalizeResponse = await _dio.post('batches/finalize', data: {
        'batch_id': batchId,
      });

      if (finalizeResponse.statusCode != 200) {
        throw Exception('Failed to finalize batch');
      }

      AppLogger.print('Batch finalized successfully!');
      return batchId;

    } on DioException catch (e) {
      AppLogger.error('Upload batch failed (DioException)', e.response?.data);
      return null;
    } catch (e) {
      AppLogger.error('Upload batch failed', e);
      return null;
    }
  }
}
