package com.example.petstoremobile.viewmodels;

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

import com.example.petstoremobile.dtos.CustomerDTO;
import com.example.petstoremobile.repositories.CustomerRepository;
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 CustomerListViewModel extends ViewModel {
    private final CustomerRepository repository;

    private final MutableLiveData<List<CustomerDTO>> customers = new MutableLiveData<>(new ArrayList<>());
    private final MutableLiveData<List<CustomerDTO>> filteredCustomers = 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;

    private String lastQuery = "";
    private String lastStatus = "All Statuses";

    @Inject
    public CustomerListViewModel(CustomerRepository repository) {
        this.repository = repository;
    }

    public LiveData<List<CustomerDTO>> getFilteredCustomers() { return filteredCustomers; }
    public LiveData<Boolean> getIsLoading() { return isLoading; }
    public boolean isLastPage() { return isLastPage; }

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

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

        if (isLastPage) return;

        isLoading.setValue(true);
        observeOnce(repository.getAllCustomers(currentPage, PAGE_SIZE), resource -> {
            if (resource != null) {
                if (resource.status == Resource.Status.SUCCESS && resource.data != null) {
                    List<CustomerDTO> currentList = reset ? new ArrayList<>() : new ArrayList<>(customers.getValue());
                    currentList.addAll(resource.data.getContent());
                    customers.setValue(currentList);
                    isLastPage = resource.data.isLast();
                    if (!isLastPage) currentPage++;
                    applyFilter(currentList);
                    isLoading.setValue(false);
                } else if (resource.status == Resource.Status.ERROR) {
                    isLoading.setValue(false);
                }
            }
        });
    }

    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 void filter(String query, String status) {
        this.lastQuery = query;
        this.lastStatus = status;
        applyFilter(customers.getValue());
    }

    private void applyFilter(List<CustomerDTO> all) {
        if (all == null) return;

        List<CustomerDTO> filtered = new ArrayList<>();
        String lowerQuery = lastQuery.toLowerCase();

        for (CustomerDTO c : all) {
            boolean matchesQuery = lastQuery.isEmpty() ||
                    (c.getFullName() != null && c.getFullName().toLowerCase().contains(lowerQuery)) ||
                    (c.getUsername() != null && c.getUsername().toLowerCase().contains(lowerQuery)) ||
                    (c.getEmail() != null && c.getEmail().toLowerCase().contains(lowerQuery)) ||
                    (c.getPhone() != null && c.getPhone().toLowerCase().contains(lowerQuery));

            boolean matchesStatus = lastStatus.equals("All Statuses") ||
                    (lastStatus.equals("Active") && Boolean.TRUE.equals(c.getActive())) ||
                    (lastStatus.equals("Inactive") && Boolean.FALSE.equals(c.getActive()));

            if (matchesQuery && matchesStatus) {
                filtered.add(c);
            }
        }
        filteredCustomers.setValue(filtered);
    }
}
