import 'dart:convert';

import 'package:shared_preferences/shared_preferences.dart';

Future<void> addItemToCart(String id) async {
  final prefs = await SharedPreferences.getInstance();
  String cartString = prefs.getString('cart') ?? "[]";
  List<Map<String, dynamic>> cart =
      List<Map<String, dynamic>>.from(jsonDecode(cartString) as List<dynamic>);
  final index = cart.indexWhere((element) => element['id'] == id);
  if (index == -1) {
    cart.add({'id': id, 'count': 1});
  } else {
    cart[index]['count'] = cart[index]['count']! + 1;
  }
  prefs.setString('cart', jsonEncode(cart));
}

Future<List<Map<String, dynamic>>> getCart() async {
  final prefs = await SharedPreferences.getInstance();
  String cartString = prefs.getString('cart') ?? "[]";
  List<Map<String, dynamic>> cart =
      List<Map<String, dynamic>>.from(jsonDecode(cartString) as List<dynamic>);
  return cart;
}

Future<void> removeItemFromCart(String id) async {
  final prefs = await SharedPreferences.getInstance();
  String cartString = prefs.getString('cart') ?? "[]";
  List<Map<String, dynamic>> cart =
      List<Map<String, dynamic>>.from(jsonDecode(cartString) as List<dynamic>);
  cart.removeWhere((element) => element['id'] == id && element['count'] == 1);
  for (final item in cart) {
    if (item['id'] == id) {
      item['count'] = item['count']! - 1;
      if (item['count'] == 0) {
        cart.remove(item);
      }
    }
  }
  prefs.setString('cart', jsonEncode(cart));
}

Future<void> clearCart() async {
  final prefs = await SharedPreferences.getInstance();
  prefs.setString('cart', "[]");
}
