import 'dart:io';
import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart' as path;

class ImageCompressionHelper {
  /// Compress and resize image to max 200x200 and ensure file size < 1MB
  /// Returns the compressed image file
  static Future<File?> compressAndResizeImage(File imageFile) async {
    try {
      // Check if file exists
      if (!await imageFile.exists()) {
        print('Image file does not exist');
        return null;
      }

      print('Original file size: ${await imageFile.length() / 1024} KB');

      // Get temporary directory
      final tempDir = await getTemporaryDirectory();
      final targetPath = path.join(
        tempDir.path,
        'compressed_${DateTime.now().millisecondsSinceEpoch}.jpg',
      );

      // Start with quality 85
      int quality = 85;
      const int maxFileSizeBytes = 1048576; // 1MB

      // Compress the image
      var result = await FlutterImageCompress.compressWithFile(
        imageFile.absolute.path,
        quality: quality,
        format: CompressFormat.jpeg,
      );

      if (result == null || result.isEmpty) {
        print('Compression returned null or empty');
        return null;
      }

      // Write to file
      File resultFile = File(targetPath);
      await resultFile.writeAsBytes(result);

      int fileSize = await resultFile.length();
      print('First compression: ${fileSize / 1024} KB, quality: $quality');

      // If file size is still > 1MB, reduce quality progressively
      int attempts = 0;
      while (fileSize > maxFileSizeBytes && quality > 10 && attempts < 10) {
        quality -= 10;
        attempts++;

        result = await FlutterImageCompress.compressWithFile(
          imageFile.absolute.path,
          quality: quality,
          format: CompressFormat.jpeg,
        );

        if (result == null || result.isEmpty) {
          print('Compression returned null on attempt $attempts');
          break;
        }

        await resultFile.writeAsBytes(result);
        fileSize = await resultFile.length();
        print('Compression attempt $attempts: ${fileSize / 1024} KB, quality: $quality');
      }

      // Final validation
      if (await resultFile.exists()) {
        final finalSize = await resultFile.length();
        print('Final compressed image size: ${finalSize / 1024} KB');

        if (finalSize > maxFileSizeBytes) {
          print('Warning: Final file size (${finalSize / 1024} KB) exceeds 1MB limit');
        }

        return resultFile;
      }

      return null;
    } catch (e, stackTrace) {
      print('Error compressing image: $e');
      print('Stack trace: $stackTrace');
      return null;
    }
  }

  /// Get file size in KB
  static Future<double> getFileSizeInKB(File file) async {
    int bytes = await file.length();
    return bytes / 1024;
  }

  /// Get file size in MB
  static Future<double> getFileSizeInMB(File file) async {
    int bytes = await file.length();
    return bytes / (1024 * 1024);
  }
}

