// ignore_for_file: use_build_context_synchronously

import 'dart:io';

import 'package:file_picker/file_picker.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:hoshan/core/services/permission/permission_service.dart';
import 'package:hoshan/ui/widgets/components/snackbar/snackbar_manager.dart';
import 'package:image_picker/image_picker.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:image_picker_android/image_picker_android.dart';
import 'package:image_picker_platform_interface/image_picker_platform_interface.dart';
// import 'package:image/image.dart' as img;

class PickFileService {
  BuildContext context;

  PickFileService(this.context);
  Future<List<XFile>?> getFile(
      {required final FileType fileType,
      bool allowMultiple = false,
      final Function(FilePickerStatus)? onFileLoading,
      final List<String>? allowedExtensions,
      final int? maxFiles,
      final int? maxSize}) async {
    try {
      if (!kIsWeb) {
        await PermissionService.getPermission(permission: Permission.storage);
      }
      FilePickerResult? result = await FilePicker.platform.pickFiles(
          allowMultiple: allowMultiple,
          type: fileType,
          onFileLoading: onFileLoading,
          allowedExtensions: allowedExtensions);

      if (result == null) return null;

      List<XFile> files = result.xFiles;
      final filteredFiles = <XFile>[];

      for (var file in files) {
        if (maxSize != null) {
          int fileSize =
              kIsWeb ? await file.length() : File(file.path).lengthSync();
          if (fileSize > maxSize * 1024 * 1024) {
            SnackBarManager(context).show(
                status: SnackBarStatus.error,
                message: 'سایز فایل ${file.name} بیشتر از حد مجاز است!');
            continue;
          }
        }
        if (allowedExtensions != null) {
          if (!allowedExtensions.contains(file.name.split('.').last)) {
            SnackBarManager(context).show(
                status: SnackBarStatus.error,
                message: 'پسوند فایل ${file.name} مجاز نیست!');
            continue;
          }
        }
        filteredFiles.add(file);
      }

      return filteredFiles;
    } catch (e) {
      if (kDebugMode) {
        print("PickFileService Error: $e");
      }
      return null;
    }
  }

  static Future<XFile?> getCameraImage() async {
    await PermissionService.getPermission(permission: Permission.camera);
    final ImagePickerPlatform imagePickerImplementation =
        ImagePickerPlatform.instance;
    if (imagePickerImplementation is ImagePickerAndroid) {
      imagePickerImplementation.useAndroidPhotoPicker = true;
    }
    final ImagePicker picker = ImagePicker();
    final XFile? image = await picker.pickImage(
      source: ImageSource.camera,
      imageQuality: 20,
    );

    return image;
  }

  static Future<bool> isImageValid(XFile file) async {
    if (file.name.split('.').last.toLowerCase() != 'jpg' &&
        file.name.split('.').last.toLowerCase() != 'jpeg' &&
        file.name.split('.').last.toLowerCase() != 'png') {
      return false;
    }

    int fileSize = kIsWeb ? await file.length() : File(file.path).lengthSync();
    final validSize = 10; // MB

    if (fileSize > validSize * 1024 * 1024) {
      return false;
    }

    // final bytes = await file.readAsBytes();
    // final image = img.decodeImage(bytes);
    // if (image == null) {
    //   return false;
    // }

    // if (image.width > 2000 || image.height > 2000) {
    //   return false;
    // }

    return true;
  }
}
