package com.example.petstoremobile.viewmodels;

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

import com.example.petstoremobile.dtos.SupplierDTO;
import com.example.petstoremobile.repositories.SupplierRepository;
import com.example.petstoremobile.utils.Resource;

import androidx.lifecycle.Observer;

import javax.inject.Inject;

import dagger.hilt.android.lifecycle.HiltViewModel;

@HiltViewModel
public class SupplierDetailViewModel extends ViewModel {
    private final SupplierRepository repository;
    private final MutableLiveData<ViewState> viewState = new MutableLiveData<>(new ViewState());

    private long supId = -1;

    @Inject
    public SupplierDetailViewModel(SupplierRepository repository) {
        this.repository = repository;
    }

    public void setSupId(long id) {
        this.supId = id;
        initMode(id != -1);
    }

    public long getSupId() {
        return supId;
    }

    public boolean isEditing() {
        ViewState current = viewState.getValue();
        return current != null && current.isEditing;
    }

    public LiveData<ViewState> getViewState() {
        return viewState;
    }

    public void initMode(boolean isEditing) {
        updateViewState(state -> {
            state.isEditing = isEditing;
            state.modeTitle = isEditing ? "Edit Supplier" : "Add Supplier";
            state.saveButtonText = isEditing ? "Save" : "Add";
            state.isSupIdVisible = isEditing;
            state.isDeleteVisible = isEditing;
            state.isFieldsEnabled = true;
        });
    }

    public LiveData<Resource<SupplierDTO>> loadSupplier() {
        MutableLiveData<Resource<SupplierDTO>> result = new MutableLiveData<>();
        observeOnce(repository.getSupplierById(supId), resource -> {
            if (resource != null && resource.status == Resource.Status.SUCCESS && resource.data != null) {
                SupplierDTO s = resource.data;
                updateViewState(state -> {
                    state.supCompany = safeText(s.getSupCompany());
                    state.supFirstName = safeText(s.getSupContactFirstName());
                    state.supLastName = safeText(s.getSupContactLastName());
                    state.supEmail = safeText(s.getSupEmail());
                    state.supPhone = safeText(s.getSupPhone());
                });
            }
            result.setValue(resource);
        });
        return result;
    }

    public LiveData<Resource<SupplierDTO>> saveSupplier(SupplierDTO dto) {
        if (isEditing()) {
            dto.setSupId(supId);
            return repository.updateSupplier(supId, dto);
        }
        return repository.createSupplier(dto);
    }

    public LiveData<Resource<Void>> deleteSupplier() {
        return repository.deleteSupplier(supId);
    }

    private String safeText(String value) {
        return value == null ? "" : value.trim();
    }

    private void updateViewState(Action<ViewState> action) {
        ViewState current = viewState.getValue();
        if (current != null) {
            action.run(current);
            viewState.setValue(current);
        }
    }

    private interface Action<T> {
        void run(T target);
    }

    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 static class ViewState {
        public boolean isEditing = false;
        public boolean isDeleteVisible = false;
        public boolean isSupIdVisible = false;
        public boolean isFieldsEnabled = true;
        public String modeTitle = "Add Supplier";
        public String saveButtonText = "Add";
        public String supCompany = "";
        public String supFirstName = "";
        public String supLastName = "";
        public String supEmail = "";
        public String supPhone = "";
    }
}
