package com.example.cuida.ui.appointments;

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.Appointment;
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 AppointmentsViewModel extends AndroidViewModel {

    private final MutableLiveData<List<Appointment>> futureAppointments = new MutableLiveData<>(new ArrayList<>());
    private final MutableLiveData<List<Appointment>> pastAppointments = new MutableLiveData<>(new ArrayList<>());
    private final FirebaseFirestore db;
    private final FirebaseAuth auth;

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

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

        Log.d("AppointmentsVM", "Fetching appointments for userId: " + userId);
        // 1. Fetch Future Appointments
        db.collection("consultas")
                .whereEqualTo("userId", userId)
                .whereEqualTo("isPast", false)
                .addSnapshotListener((value, error) -> {
                    if (error != null) {
                        Log.e("AppointmentsVM", "Listen failed for future.", error);
                        return;
                    }

                    if (value != null) {
                        Log.d("AppointmentsVM", "Future appointments received. Count: " + value.size());
                    }

                    List<Appointment> apps = new ArrayList<>();
                    java.util.Date now = new java.util.Date();
                    java.text.SimpleDateFormat format = new java.text.SimpleDateFormat("dd/MM/yyyy HH:mm",
                            java.util.Locale.getDefault());

                    if (value != null) {
                        for (QueryDocumentSnapshot doc : value) {
                            Appointment app = doc.toObject(Appointment.class);
                            try {
                                java.util.Date appDate = format.parse(app.date + " " + app.time);
                                if (appDate != null && appDate.before(now)) {
                                    // It passed out of date. Update in DB to move it to Past Appointments.
                                    db.collection("consultas").document(doc.getId()).update("isPast", true);
                                } else {
                                    apps.add(app);
                                }
                            } catch (java.text.ParseException e) {
                                apps.add(app);
                            }
                        }
                    }

                    // Sort locally
                    apps.sort((a, b) -> {
                        try {
                            java.util.Date dateA = format.parse(a.date + " " + a.time);
                            java.util.Date dateB = format.parse(b.date + " " + b.time);
                            return dateA.compareTo(dateB);
                        } catch (java.text.ParseException e) {
                            return 0;
                        }
                    });

                    futureAppointments.setValue(apps);
                });

        // 2. Fetch Past Appointments
        db.collection("consultas")
                .whereEqualTo("userId", userId)
                .whereEqualTo("isPast", true)
                .addSnapshotListener((value, error) -> {
                    if (error != null) {
                        Log.e("AppointmentsVM", "Listen failed for past.", error);
                        return;
                    }

                    if (value != null) {
                        Log.d("AppointmentsVM", "Past appointments received. Count: " + value.size());
                    }

                    List<Appointment> apps = new ArrayList<>();
                    if (value != null) {
                        for (QueryDocumentSnapshot doc : value) {
                            apps.add(doc.toObject(Appointment.class));
                        }
                    }

                    // Sort locally descending
                    java.text.SimpleDateFormat format = new java.text.SimpleDateFormat("dd/MM/yyyy HH:mm",
                            java.util.Locale.getDefault());
                    apps.sort((a, b) -> {
                        try {
                            java.util.Date dateA = format.parse(a.date + " " + a.time);
                            java.util.Date dateB = format.parse(b.date + " " + b.time);
                            if (dateA == null || dateB == null) return 0;
                            return dateB.compareTo(dateA); // Reverse for descending
                        } catch (java.text.ParseException e) {
                            return 0;
                        }
                    });

                    pastAppointments.setValue(apps);
                });
    }

    public LiveData<List<Appointment>> getFutureAppointments() {
        return futureAppointments;
    }

    public LiveData<List<Appointment>> getPastAppointments() {
        return pastAppointments;
    }

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

        appointment.userId = userId;

        db.collection("consultas")
                .add(appointment)
                .addOnSuccessListener(documentReference -> Log.d("AppointmentsVM", "Appointment added"))
                .addOnFailureListener(e -> Log.w("AppointmentsVM", "Error adding appointment", e));
    }
}
