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.DropdownDTO;
import com.example.petstoremobile.dtos.PetDTO;
import com.example.petstoremobile.dtos.StoreDTO;
import com.example.petstoremobile.repositories.PetRepository;
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 PetListViewModel extends ViewModel {
    private final PetRepository petRepository;
    private final StoreRepository storeRepository;

    private final MutableLiveData<List<PetDTO>> pets = new MutableLiveData<>(new ArrayList<>());
    private final MutableLiveData<List<StoreDTO>> stores = new MutableLiveData<>(new ArrayList<>());
    private final MutableLiveData<List<String>> speciesOptions = 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 PetListViewModel(PetRepository petRepository, StoreRepository storeRepository) {
        this.petRepository = petRepository;
        this.storeRepository = storeRepository;
    }

    public LiveData<List<PetDTO>> getPets() { return pets; }
    public LiveData<List<StoreDTO>> getStores() { return stores; }
    public LiveData<List<String>> getSpeciesOptions() { return speciesOptions; }
    public LiveData<Boolean> getIsLoading() { return isLoading; }
    public boolean isLastPage() { return isLastPage; }

    public void loadPets(boolean reset, String query, String status, String species, Long storeId) {
        if (isLoading.getValue() != null && isLoading.getValue() && !reset) return;

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

        if (isLastPage) return;

        if ("All Statuses".equals(status)) status = null;
        if ("All Species".equals(species)) species = null;

        isLoading.setValue(true);
        final String finalStatus = status;
        final String finalSpecies = species;
        observeOnce(petRepository.getAllPets(currentPage, PAGE_SIZE, query, finalStatus, finalSpecies, storeId, null, "petName"), resource -> {
            if (resource != null) {
                if (resource.status == Resource.Status.SUCCESS && resource.data != null) {
                    List<PetDTO> currentList = reset ? new ArrayList<>() : new ArrayList<>(pets.getValue());
                    currentList.addAll(resource.data.getContent());
                    pets.setValue(currentList);
                    isLastPage = resource.data.isLast();
                    if (!isLastPage) currentPage++;
                    isLoading.setValue(false);
                } else if (resource.status == Resource.Status.ERROR) {
                    isLoading.setValue(false);
                }
            }
        });
    }

    public void loadSpecies() {
        observeOnce(petRepository.getPetSpeciesDropdowns(), resource -> {
            if (resource != null && resource.status == Resource.Status.SUCCESS && resource.data != null) {
                List<String> labels = new ArrayList<>();
                labels.add("All Species");
                for (DropdownDTO dto : resource.data) {
                    labels.add(dto.getLabel());
                }
                speciesOptions.setValue(labels);
            }
        });
    }

    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);
            }
        });
    }

    public LiveData<Resource<Void>> bulkDeletePets(List<String> ids) {
        return petRepository.bulkDeletePets(new BulkDeleteRequest(ids));
    }
}
