import 'dart:io';

import 'package:dio/dio.dart';
import 'package:mime/mime.dart';
import 'package:path/path.dart' as path;

/// Utility class for validating images
class ImageValidator {
  // Allowed image extensions
  static const List<String> allowedExtensions = ['.jpg', '.jpeg', '.png'];

  // Allowed MIME types
  static const List<String> allowedMimeTypes = ['image/jpeg', 'image/png'];

  /// Maximum file size in bytes (4MB)
  static const int maxFileSizeBytes = 4 * 1024 * 1024;

  /// Validate if the file is a valid image based on extension
  static bool isValidImageExtension(String filePath) {
    final extension = path.extension(filePath).toLowerCase();
    return allowedExtensions.contains(extension);
  }

  /// Get the MIME type for a file
  static DioMediaType getMimeType(String filePath) {
    final extension = path.extension(filePath).toLowerCase();

    if (extension == '.jpg' || extension == '.jpeg') {
      return DioMediaType.parse('image/jpeg');
    } else if (extension == '.png') {
      return DioMediaType.parse('image/png');
    }

    // Use mime package for detecting MIME type
    final mimeType = lookupMimeType(filePath) ?? 'application/octet-stream';
    return DioMediaType.parse(mimeType);
  }

  /// Check if a file is within size limits
  static Future<bool> isFileSizeValid(String filePath) async {
    try {
      final file = File(filePath);
      final size = await file.length();
      return size <= maxFileSizeBytes;
    } catch (e) {
      return false;
    }
  }

  /// Complete validation of an image file
  static Future<bool> isValidImage(String filePath) async {
    // Check extension
    if (!isValidImageExtension(filePath)) {
      return false;
    }

    // Check file size
    if (!await isFileSizeValid(filePath)) {
      return false;
    }

    return true;
  }

  /// Synchronous validation for extension and format
  static bool isValidImageFile(String filePath) {
    return isValidImageExtension(filePath);
  }

  /// Format error for invalid images
  static String getInvalidImageError(String imageType) {
    return 'Please upload a valid $imageType image (JPG, JPEG, or PNG under 4MB)';
  }
}
