package com.example.cuida.ui.home;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import com.example.cuida.databinding.FragmentHomeBinding;
import com.example.cuida.ui.medication.MedicationViewModel;
import com.example.cuida.ui.appointments.AppointmentsViewModel;
import com.example.cuida.data.model.Appointment;
import java.util.Calendar;
import java.util.Locale;

public class HomeFragment extends Fragment {

    private FragmentHomeBinding binding;
    private MedicationViewModel medicationViewModel;
    private AppointmentsViewModel appointmentsViewModel;

    public View onCreateView(@NonNull LayoutInflater inflater,
            ViewGroup container, Bundle savedInstanceState) {
        binding = FragmentHomeBinding.inflate(inflater, container, false);

        // --- Greeting & Profile Picture ---
        com.google.firebase.auth.FirebaseAuth auth = com.google.firebase.auth.FirebaseAuth.getInstance();
        if (auth.getCurrentUser() != null) {
            String userId = auth.getCurrentUser().getUid();
            com.google.firebase.firestore.FirebaseFirestore.getInstance().collection("utilizadores").document(userId)
                    .get()
                    .addOnSuccessListener(documentSnapshot -> {
                        if (documentSnapshot.exists() && isAdded()) {
                            String name = documentSnapshot.getString("name");
                            if (name != null && !name.isEmpty()) {
                                // Extract first name
                                String firstName = name.split(" ")[0];
                                binding.textGreeting.setText("Olá, " + firstName + "!");
                            } else {
                                binding.textGreeting.setText("Olá, Utilizador!");
                            }
                            
                            // Load Profile Picture
                            String profilePictureUri = documentSnapshot.getString("profilePictureUri");
                            if (profilePictureUri != null && !profilePictureUri.isEmpty()) {
                                try {
                                    binding.imageProfileHome.setImageURI(android.net.Uri.parse(profilePictureUri));
                                } catch (Exception e) {
                                    android.util.Log.e("HomeFragment", "Error loading profile pic view: " + e.getMessage());
                                }
                            }
                        }
                    })
                    .addOnFailureListener(e -> {
                        if (isAdded())
                            binding.textGreeting.setText("Olá, Utilizador!");
                    });
        } else {
            binding.textGreeting.setText("Olá, Utilizador!");
        }

        // --- Next Medication ---
        medicationViewModel = new ViewModelProvider(this).get(MedicationViewModel.class);
        medicationViewModel.getNextMedication().observe(getViewLifecycleOwner(), medication -> {
            if (medication != null) {
                binding.nextMedName.setText(medication.name + " (" + medication.dosage + ")");
                binding.nextMedTime.setText("Hoje, " + medication.time);
            } else {
                binding.nextMedName.setText("Sem medicação");
                binding.nextMedTime.setText("--:--");
            }
        });

        // --- Book Appointment ---
        appointmentsViewModel = new ViewModelProvider(this).get(AppointmentsViewModel.class);
        binding.buttonBookAppointment.setOnClickListener(v -> {
            androidx.navigation.Navigation.findNavController(v)
                    .navigate(com.example.cuida.R.id.action_home_to_schedule_appointment);
        });

        return binding.getRoot();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }
}
