package com.example.petstoremobile.viewmodels;

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

import com.example.petstoremobile.dtos.ActivityLogDTO;
import com.example.petstoremobile.dtos.DropdownDTO;
import com.example.petstoremobile.repositories.ActivityLogRepository;
import com.example.petstoremobile.repositories.StoreRepository;
import com.example.petstoremobile.utils.Resource;

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

import javax.inject.Inject;

import dagger.hilt.android.lifecycle.HiltViewModel;

@HiltViewModel
public class ActivityLogListViewModel extends ViewModel {
    private static final int PAGE_SIZE = 20;

    private final ActivityLogRepository repository;
    private final StoreRepository storeRepository;

    private final MutableLiveData<List<ActivityLogDTO>> logs = new MutableLiveData<>(new ArrayList<>());
    private final MutableLiveData<List<DropdownDTO>> storeOptions = new MutableLiveData<>(new ArrayList<>());
    private final MutableLiveData<Boolean> isLoading = new MutableLiveData<>(false);

    private Long currentStoreId = null;
    private String currentRole = null;
    private String currentSearch = null;
    private String currentStartDate = null;
    private String currentEndDate = null;

    private int currentLimit = PAGE_SIZE;
    private boolean isLastPage = false;

    @Inject
    public ActivityLogListViewModel(ActivityLogRepository repository, StoreRepository storeRepository) {
        this.repository = repository;
        this.storeRepository = storeRepository;
    }

    public LiveData<List<ActivityLogDTO>> getLogs() { return logs; }
    public LiveData<List<DropdownDTO>> getStoreOptions() { return storeOptions; }
    public LiveData<Boolean> getIsLoading() { return isLoading; }
    public boolean isLastPage() { return isLastPage; }

    public void loadInitialData() {
        loadStores();
        loadLogs(true);
    }

    private void loadStores() {
        observeOnce(storeRepository.getStoreDropdowns(), resource -> {
            if (resource != null && resource.status == Resource.Status.SUCCESS && resource.data != null) {
                storeOptions.setValue(resource.data);
            }
        });
    }

    public void loadLogs(boolean reset) {
        if (isLoading.getValue() != null && isLoading.getValue() && !reset) return;

        if (reset) {
            currentLimit = PAGE_SIZE;
            isLastPage = false;
        }

        if (isLastPage) return;

        isLoading.setValue(true);
        observeOnce(repository.getActivityLogs(currentLimit, currentStoreId, currentRole, currentSearch, currentStartDate, currentEndDate), resource -> {
            if (resource != null) {
                if (resource.status == Resource.Status.SUCCESS && resource.data != null) {
                    List<ActivityLogDTO> result = resource.data;
                    logs.setValue(result);
                    isLastPage = result.size() < currentLimit;
                    if (!isLastPage) currentLimit += PAGE_SIZE;
                    isLoading.setValue(false);
                } else if (resource.status == Resource.Status.ERROR) {
                    isLoading.setValue(false);
                }
            }
        });
    }

    public void setRoleFilter(String role) {
        currentRole = "All Roles".equals(role) ? null : role;
        loadLogs(true);
    }

    public void setStoreFilter(Long storeId) {
        currentStoreId = storeId;
        loadLogs(true);
    }

    public void setSearchQuery(String query) {
        currentSearch = (query == null || query.trim().isEmpty()) ? null : query.trim();
        loadLogs(true);
    }

    public void setDateRange(String startDate, String endDate) {
        currentStartDate = startDate;
        currentEndDate = endDate;
        loadLogs(true);
    }


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