import 'dart:io';
import 'dart:typed_data';
import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart' as path;
import 'package:on_field_work/helpers/services/app_logger.dart'; 



Future<Uint8List?> compressImageToUnder100KB(File file) async {
  int quality = 40;
  Uint8List? result;

  const int maxWidth = 800;
  const int maxHeight = 800;

  logSafe("Starting image compression...",  );

  while (quality >= 10) {
    try {
      result = await FlutterImageCompress.compressWithFile(
        file.absolute.path,
        quality: quality,
        minWidth: maxWidth,
        minHeight: maxHeight,
        format: CompressFormat.jpeg,
      );

      if (result != null) {
        logSafe(
          'Compression quality: $quality, size: ${(result.lengthInBytes / 1024).toStringAsFixed(2)} KB',
        );

        if (result.lengthInBytes <= 100 * 1024) {
          logSafe("Image compressed successfully under 100KB.");
          return result;
        }
      } else {
        logSafe("Compression returned null at quality $quality", level: LogLevel.warning);
      }
    } catch (e, stacktrace) {
      logSafe("Compression error at quality $quality", level: LogLevel.error, error: e, stackTrace: stacktrace);
    }

    quality -= 10;
  }

  logSafe("Failed to compress image under 100KB. Returning best effort result.", level: LogLevel.warning);
  return result;
}

Future<File> saveCompressedImageToFile(Uint8List bytes) async {
  try {
    final tempDir = await getTemporaryDirectory();
    final filePath = path.join(
      tempDir.path,
      'compressed_${DateTime.now().millisecondsSinceEpoch}.jpg',
    );
    final file = File(filePath);
    final savedFile = await file.writeAsBytes(bytes);

    logSafe("Compressed image saved to ${savedFile.path}",  );
    return savedFile;
  } catch (e, stacktrace) {
    logSafe("Error saving compressed image", level: LogLevel.error, error: e, stackTrace: stacktrace);
    rethrow;
  }
}
