package com.brisco.meatwholesaler;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

public class CartManager {
    private static final String PREFS_NAME = "BriscoCart";
    private static final String CART_KEY = "cart_items";
    private static CartManager instance;
    private Context context;
    private SharedPreferences preferences;
    private Gson gson;
    private List<Product> cartItems;

    private CartManager(Context context) {
        this.context = context.getApplicationContext();
        this.preferences = this.context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        this.gson = new Gson();
        this.cartItems = loadCart();
    }

    public static synchronized CartManager getInstance(Context context) {
        if (instance == null) {
            instance = new CartManager(context);
        }
        return instance;
    }

    private List<Product> loadCart() {
        String cartJson = preferences.getString(CART_KEY, "");
        if (cartJson.isEmpty()) {
            return new ArrayList<>();
        }
        
        try {
            Type type = new TypeToken<List<Product>>() {}.getType();
            return gson.fromJson(cartJson, type);
        } catch (Exception e) {
            Log.e("CartManager", "Error loading cart", e);
            return new ArrayList<>();
        }
    }

    private void saveCart() {
        String cartJson = gson.toJson(cartItems);
        preferences.edit().putString(CART_KEY, cartJson).apply();
    }

    public void addProduct(Product product) {
        cartItems.add(product);
        saveCart();
    }

    public void removeProduct(int position) {
        if (position >= 0 && position < cartItems.size()) {
            cartItems.remove(position);
            saveCart();
        }
    }

    public void updateProduct(int position, Product product) {
        if (position >= 0 && position < cartItems.size()) {
            cartItems.set(position, product);
            saveCart();
        }
    }

    public void clearCart() {
        cartItems.clear();
        saveCart();
    }

    public List<Product> getCartItems() {
        return new ArrayList<>(cartItems);
    }

    public int getCartCount() {
        return cartItems.size();
    }

    public double getCartTotal() {
        double total = 0.0;
        for (Product product : cartItems) {
            total += product.getPrice();
        }
        return total;
    }

    public String getFormattedTotal() {
        return String.format("R %.2f", getCartTotal());
    }

    public boolean isEmpty() {
        return cartItems.isEmpty();
    }

    public Product getProductAt(int position) {
        if (position >= 0 && position < cartItems.size()) {
            return cartItems.get(position);
        }
        return null;
    }

    public void addProduct(Product product, int quantity) {
        for (int i = 0; i < quantity; i++) {
            cartItems.add(new Product(
                product.getId(),
                product.getName(),
                product.getPrice(),
                product.getDescription(),
                product.getImageUrl(),
                product.getCategory()
            ));
        }
        saveCart();
    }

    public int getProductQuantity(Product product) {
        int count = 0;
        for (Product item : cartItems) {
            if (item.getId().equals(product.getId())) {
                count++;
            }
        }
        return count;
    }

    public void removeProducts(Product product, int quantity) {
        int removed = 0;
        for (int i = cartItems.size() - 1; i >= 0 && removed < quantity; i--) {
            if (cartItems.get(i).getId().equals(product.getId())) {
                cartItems.remove(i);
                removed++;
            }
        }
        saveCart();
    }
}
