package com.example.petstoremobile.viewmodels;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import com.example.petstoremobile.dtos.BulkDeleteRequest;
import com.example.petstoremobile.dtos.InventoryDTO;
import com.example.petstoremobile.dtos.StoreDTO;
import com.example.petstoremobile.repositories.InventoryRepository;
import com.example.petstoremobile.repositories.StoreRepository;
import com.example.petstoremobile.utils.Resource;

import androidx.lifecycle.Observer;

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

import javax.inject.Inject;

import dagger.hilt.android.lifecycle.HiltViewModel;

@HiltViewModel
public class InventoryListViewModel extends ViewModel {
    private final InventoryRepository inventoryRepository;
    private final StoreRepository storeRepository;

    private final MutableLiveData<List<InventoryDTO>> inventory = new MutableLiveData<>(new ArrayList<>());
    private final MutableLiveData<List<StoreDTO>> stores = new MutableLiveData<>(new ArrayList<>());
    private final MutableLiveData<Boolean> isLoading = new MutableLiveData<>(false);
    
    private int currentPage = 0;
    private boolean isLastPage = false;
    private static final int PAGE_SIZE = 20;

    @Inject
    public InventoryListViewModel(InventoryRepository inventoryRepository, StoreRepository storeRepository) {
        this.inventoryRepository = inventoryRepository;
        this.storeRepository = storeRepository;
    }

    /**
     * Returns the LiveData for the inventory list.
     */
    public LiveData<List<InventoryDTO>> getInventory() { return inventory; }

    /**
     * Returns the LiveData for the store list for filtering.
     */
    public LiveData<List<StoreDTO>> getStores() { return stores; }

    /**
     * Returns the LiveData for the loading state.
     */
    public LiveData<Boolean> getIsLoading() { return isLoading; }

    /**
     * Checks if the last page of inventory has been reached.
     */
    public boolean isLastPage() { return isLastPage; }

    /**
     * Loads inventory items from the repository with the specified filters.
     */
    public void loadInventory(boolean reset, String query, Long storeId) {
        if (isLoading.getValue() != null && isLoading.getValue() && !reset) return;

        if (reset) {
            currentPage = 0;
            isLastPage = false;
        }

        isLoading.setValue(true);
        observeOnce(inventoryRepository.getAllInventory(query, storeId, currentPage, PAGE_SIZE, "product.prodName"), resource -> {
            if (resource != null) {
                if (resource.status == Resource.Status.SUCCESS && resource.data != null) {
                    List<InventoryDTO> currentList = reset ? new ArrayList<>() : new ArrayList<>(inventory.getValue());
                    currentList.addAll(resource.data.getContent());
                    inventory.setValue(currentList);
                    isLastPage = resource.data.isLast();
                    if (!isLastPage) currentPage++;
                    isLoading.setValue(false);
                } else if (resource.status == Resource.Status.ERROR) {
                    isLoading.setValue(false);
                }
            }
        });
    }

    /**
     * Loads the list of stores for filtering options.
     */
    public void loadStores() {
        observeOnce(storeRepository.getAllStores(0, 100), resource -> {
            if (resource != null && resource.status == Resource.Status.SUCCESS && resource.data != null) {
                stores.setValue(resource.data.getContent());
            }
        });
    }

    private <T> void observeOnce(LiveData<Resource<T>> liveData, Observer<Resource<T>> handler) {
        liveData.observeForever(new Observer<Resource<T>>() {
            @Override
            public void onChanged(Resource<T> resource) {
                if (resource == null || resource.status != Resource.Status.LOADING) {
                    liveData.removeObserver(this);
                }
                handler.onChanged(resource);
            }
        });
    }

    /**
     * Deletes multiple inventory items by their IDs.
     */
    public LiveData<Resource<Void>> bulkDeleteInventory(List<String> ids) {
        List<Long> longIds = ids.stream().map(Long::valueOf).collect(java.util.stream.Collectors.toList());
        return inventoryRepository.bulkDeleteInventory(new BulkDeleteRequest(longIds));
    }
}
