import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
import '../models/movie.dart';

class LocalStorageService {
  static const String _favoritesKey = 'favorite_movies';

  static Future<bool> addToFavorites(Movie movie) async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final favoritesJson = prefs.getStringList(_favoritesKey) ?? [];
      
      final existing = favoritesJson.any((json) {
        final movieData = jsonDecode(json);
        return movieData['id'] == movie.id;
      });
      
      if (existing) {
        return false;
      }
      
      final movieJson = jsonEncode({
        'id': movie.id,
        'title': movie.title,
        'description': movie.description,
        'imageUrl': movie.imageUrl,
        'category': movie.category,
        'director': movie.director,
        'releaseDate': movie.releaseDate,
        'rating': movie.rating,
        'originalTitle': movie.originalTitle,
        'addedAt': DateTime.now().toIso8601String(),
      });
      
      favoritesJson.add(movieJson);
      await prefs.setStringList(_favoritesKey, favoritesJson);
      
      return true;
    } catch (e) {
      print('Erreur lors de l\'ajout aux favoris: $e');
      return false;
    }
  }

  static Future<bool> removeFromFavorites(int movieId) async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final favoritesJson = prefs.getStringList(_favoritesKey) ?? [];
      
      final updatedFavorites = favoritesJson.where((json) {
        final movieData = jsonDecode(json);
        return movieData['id'] != movieId;
      }).toList();
      
      if (updatedFavorites.length != favoritesJson.length) {
        await prefs.setStringList(_favoritesKey, updatedFavorites);
        return true;
      }
      
      return false;
    } catch (e) {
      print('Erreur lors de la suppression des favoris: $e');
      return false;
    }
  }

  static Future<bool> isFavorite(int movieId) async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final favoritesJson = prefs.getStringList(_favoritesKey) ?? [];
      
      return favoritesJson.any((json) {
        final movieData = jsonDecode(json);
        return movieData['id'] == movieId;
      });
    } catch (e) {
      print('Erreur lors de la vérification des favoris: $e');
      return false;
    }
  }

  static Future<List<Movie>> getFavorites() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final favoritesJson = prefs.getStringList(_favoritesKey) ?? [];
      
      return favoritesJson.map((json) {
        final movieData = jsonDecode(json);
        return Movie(
          id: movieData['id'],
          title: movieData['title'],
          description: movieData['description'],
          imageUrl: movieData['imageUrl'],
          category: movieData['category'],
          director: movieData['director'],
          releaseDate: movieData['releaseDate'],
          rating: (movieData['rating'] ?? 0.0).toDouble(),
          originalTitle: movieData['originalTitle'] ?? '',
          isFeatured: false,
        );
      }).toList();
    } catch (e) {
      print('Erreur lors de la récupération des favoris: $e');
      return [];
    }
  }
}

