import 'dart:io';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:image_picker/image_picker.dart';
import 'error_service.dart';

class ProfileImageService {
  static final FirebaseStorage _storage = FirebaseStorage.instance;
  final ImagePicker _picker = ImagePicker();
  final ErrorService _errorService = ErrorService();

  Future<String?> uploadCustomProfileImage(
    String userId,
    XFile imageFile,
  ) async {
    try {
      final ref = _storage.ref().child('profile_images').child('$userId.jpg');
      final uploadTask = ref.putFile(File(imageFile.path));
      final snapshot = await uploadTask;
      return await snapshot.ref.getDownloadURL();
    } catch (e) {
      _errorService.logError(
        'ProfileImageService',
        'Erreur lors du téléchargement de l\'image de profil pour $userId: $e',
      );
      return null;
    }
  }

  Future<XFile?> pickProfileImageFromGallery() async {
    try {
      final XFile? image = await _picker.pickImage(source: ImageSource.gallery);
      return image;
    } catch (e) {
      _errorService.logError(
        'ProfileImageService',
        'Erreur lors de la sélection de l\'image depuis la galerie: $e',
      );
      return null;
    }
  }

  Future<XFile?> takePhoto() async {
    try {
      final XFile? photo = await _picker.pickImage(source: ImageSource.camera);
      return photo;
    } catch (e) {
      _errorService.logError(
        'ProfileImageService',
        'Erreur lors de la prise de photo: $e',
      );
      return null;
    }
  }
}
