package com.example.cuida.ui.medication;

import android.app.Application;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;

import com.example.cuida.data.model.Medication;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.Query;
import com.google.firebase.firestore.QueryDocumentSnapshot;

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

public class MedicationViewModel extends AndroidViewModel {

    private final MutableLiveData<List<Medication>> allMedications = new MutableLiveData<>(new ArrayList<>());
    private final MutableLiveData<Medication> nextMedication = new MutableLiveData<>(null);
    private final FirebaseFirestore db;
    private final FirebaseAuth auth;

    public MedicationViewModel(@NonNull Application application) {
        super(application);
        db = FirebaseFirestore.getInstance();
        auth = FirebaseAuth.getInstance();
        fetchMedications();
    }

    private void fetchMedications() {
        if (auth.getCurrentUser() == null)
            return;
        String userId = auth.getCurrentUser().getUid();

        db.collection("medicamentos")
                .whereEqualTo("userId", userId)
                .addSnapshotListener((value, error) -> {
                    if (error != null) {
                        Log.e("MedicationViewModel", "Listen failed.", error);
                        return;
                    }

                    List<Medication> meds = new ArrayList<>();
                    if (value != null) {
                        for (QueryDocumentSnapshot doc : value) {
                            Medication med = doc.toObject(Medication.class);
                            med.id = doc.getId(); // Ensure ID is set
                            meds.add(med);
                        }
                    }

                    // Sort locally to avoid needing a composite index in Firestore
                    meds.sort((m1, m2) -> {
                        if (m1.time == null && m2.time == null) return 0;
                        if (m1.time == null) return 1;
                        if (m2.time == null) return -1;
                        return m1.time.compareTo(m2.time);
                    });

                    allMedications.setValue(meds);

                    if (!meds.isEmpty()) {
                        nextMedication.setValue(meds.get(0));
                    } else {
                        nextMedication.setValue(null);
                    }
                });
    }

    public LiveData<List<Medication>> getAllMedications() {
        return allMedications;
    }

    public LiveData<Medication> getNextMedication() {
        return nextMedication;
    }

    public void insert(Medication medication) {
        if (auth.getCurrentUser() == null)
            return;
        String userId = auth.getCurrentUser().getUid();

        medication.userId = userId;

        db.collection("medicamentos")
                .add(medication)
                .addOnSuccessListener(documentReference -> Log.d("MedicationViewModel", "Medication added"))
                .addOnFailureListener(e -> Log.w("MedicationViewModel", "Error adding medication", e));
    }

    public void update(Medication medication) {
        if (auth.getCurrentUser() == null || medication.id == null)
            return;
        String userId = auth.getCurrentUser().getUid();

        medication.userId = userId;

        db.collection("medicamentos")
                .document(medication.id)
                .set(medication)
                .addOnSuccessListener(aVoid -> Log.d("MedicationViewModel", "Medication updated"))
                .addOnFailureListener(e -> Log.w("MedicationViewModel", "Error updating medication", e));
    }

    public void delete(Medication medication) {
        if (auth.getCurrentUser() == null || medication.id == null)
            return;

        db.collection("medicamentos")
                .document(medication.id)
                .delete()
                .addOnSuccessListener(aVoid -> Log.d("MedicationViewModel", "Medication deleted"))
                .addOnFailureListener(e -> Log.w("MedicationViewModel", "Error deleting medication", e));
    }
}
