package com.example.cuida.ui.home;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.Navigation;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.bumptech.glide.Glide;
import com.example.cuida.R;
import com.example.cuida.data.model.Appointment;
import com.example.cuida.databinding.FragmentHomeBinding;
import com.example.cuida.ui.appointments.AppointmentAdapter;
import com.example.cuida.ui.appointments.AppointmentsViewModel;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;

import java.util.List;

public class HomeFragment extends Fragment {

    private FragmentHomeBinding binding;
    private AppointmentAdapter appointmentAdapter;

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

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        // --- Greeting & Profile Picture (Real-time) ---
        FirebaseAuth auth = FirebaseAuth.getInstance();
        if (auth.getCurrentUser() != null) {
            String userId = auth.getCurrentUser().getUid();
            FirebaseFirestore db = FirebaseFirestore.getInstance();
            
            // Listen to 'utilizadores' for basic profile info
            db.collection("utilizadores").document(userId)
                    .addSnapshotListener((documentSnapshot, error) -> {
                        if (error != null) {
                            Log.e("HomeFragment", "Error loading profile", error);
                            return;
                        }
                        if (documentSnapshot != null && documentSnapshot.exists() && isAdded()) {
                            updateGreetingUI(documentSnapshot);
                        }
                    });
            
            // Also listen to 'Pacientes' (collection where Professional app saves data)
            db.collection("Pacientes").document(userId)
                    .addSnapshotListener((documentSnapshot, error) -> {
                        if (error != null) {
                            Log.e("HomeFragment", "Error loading paciente profile", error);
                            return;
                        }
                        if (documentSnapshot != null && documentSnapshot.exists() && isAdded()) {
                            updateGreetingUI(documentSnapshot);
                        }
                    });
        } else {
            binding.textGreeting.setText(R.string.hello);
        }

        // --- Setup Adapters ---
        appointmentAdapter = new AppointmentAdapter();
        binding.recyclerAppointments.setLayoutManager(new LinearLayoutManager(requireContext()));
        binding.recyclerAppointments.setAdapter(appointmentAdapter);

        // Schedule Button
        binding.buttonSchedule.setOnClickListener(v -> 
                Navigation.findNavController(v).navigate(R.id.action_home_to_schedule_appointment));

        // --- Load Appointments ---
        AppointmentsViewModel appointmentsViewModel = new ViewModelProvider(this).get(AppointmentsViewModel.class);
        appointmentsViewModel.getFutureAppointments().observe(getViewLifecycleOwner(), (List<Appointment> appointments) -> {
            if (appointments != null && !appointments.isEmpty()) {
                binding.recyclerAppointments.setVisibility(View.VISIBLE);
                binding.textEmptyAppointments.setVisibility(View.GONE);
                appointmentAdapter.setAppointments(appointments);
            } else {
                binding.recyclerAppointments.setVisibility(View.GONE);
                binding.textEmptyAppointments.setVisibility(View.VISIBLE);
            }
        });
    }

    private void updateGreetingUI(DocumentSnapshot documentSnapshot) {
        if (!isAdded() || binding == null) return;

        String name = documentSnapshot.getString("nome_completo");
        if (name == null || name.isEmpty()) name = documentSnapshot.getString("name");
        if (name == null || name.isEmpty()) name = documentSnapshot.getString("nome");
        
        if (name != null && !name.isEmpty()) {
            String firstName = name.split(" ")[0];
            binding.textGreeting.setText(getString(R.string.hello_user, firstName));
        }

        String profilePictureUri = documentSnapshot.getString("profilePictureUri");
        binding.imageProfileHome.setVisibility(View.VISIBLE);
        if (profilePictureUri != null && !profilePictureUri.isEmpty()) {
            Glide.with(this)
                .load(profilePictureUri)
                .placeholder(R.drawable.ic_user)
                .circleCrop()
                .into(binding.imageProfileHome);
        } else {
            binding.imageProfileHome.setImageResource(R.drawable.ic_user);
        }
        
        // Clique para entrar no perfil
        binding.imageProfileHome.setOnClickListener(v -> 
                Navigation.findNavController(v).navigate(R.id.navigation_profile));
    }

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