package com.example.petstoremobile.utils;

import java.util.ArrayList;
import java.util.List;

/**
 * Helper class to manage selection state in Adapters for bulk operations.
 * Uses String keys to support both Long IDs and composite keys.
 */
public class SelectionHelper {

    private final List<String> selectedKeys = new ArrayList<>();
    private boolean selectionMode = false;
    private final SelectionListener listener;

    /**
     * Listener interface to observe selection state changes.
     */
    public interface SelectionListener {
        /**
         * Called when the number of selected items changes.
         */
        void onSelectionChanged(int count);

        /**
         * Called when selection mode is enabled or disabled.
         */
        void onSelectionModeToggle(boolean selectionMode);
    }

    /**
     * Initializes the helper with a listener.
     */
    public SelectionHelper(SelectionListener listener) {
        this.listener = listener;
    }

    /**
     * Toggles the selection state of a specific key.
     * Automatically exits selection mode if the last item is deselected.
     */
    public void toggleSelection(String key) {
        if (key == null) return;

        if (selectedKeys.contains(key)) {
            selectedKeys.remove(key);
        } else {
            selectedKeys.add(key);
        }

        listener.onSelectionChanged(selectedKeys.size());

        if (selectedKeys.isEmpty() && selectionMode) {
            selectionMode = false;
            listener.onSelectionModeToggle(false);
        }
    }

    /**
     * Enters selection mode and selects the specified key.
     */
    public void startSelection(String key) {
        if (key == null) return;
        selectionMode = true;
        selectedKeys.add(key);
        listener.onSelectionChanged(selectedKeys.size());
        listener.onSelectionModeToggle(true);
    }

    /**
     * Checks if a specific key is currently selected.
     */
    public boolean isSelected(String key) {
        return selectedKeys.contains(key);
    }

    /**
     * Checks if the helper is currently in selection mode.
     */
    public boolean isInSelectionMode() {
        return selectionMode;
    }

    /**
     * Returns a copy of the list of currently selected keys.
     */
    public List<String> getSelectedKeys() {
        return new ArrayList<>(selectedKeys);
    }

    /**
     * Clears all selections and exits selection mode.
     */
    public void clearSelection() {
        selectedKeys.clear();
        selectionMode = false;
        listener.onSelectionChanged(0);
        listener.onSelectionModeToggle(false);
    }
}
