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 android.app.TimePickerDialog;
import android.widget.Toast;
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 ---
        SharedPreferences prefs = requireContext().getSharedPreferences("prefs", Context.MODE_PRIVATE);
        String name = prefs.getString("user_name", "Utilizador");
        binding.textGreeting.setText("Olá, " + name + "!");

        // --- 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 -> showTimePicker());

        return binding.getRoot();
    }

    private void showTimePicker() {
        Calendar mcurrentTime = Calendar.getInstance();
        int hour = mcurrentTime.get(Calendar.HOUR_OF_DAY);
        int minute = mcurrentTime.get(Calendar.MINUTE);

        TimePickerDialog mTimePicker;
        mTimePicker = new TimePickerDialog(getContext(), (timePicker, selectedHour, selectedMinute) -> {
            // Round to 15 minutes
            int roundedMinute = (selectedMinute / 15) * 15;
            String time = String.format(Locale.getDefault(), "%02d:%02d", selectedHour, roundedMinute);

            // For MVP, assume date is tomorrow (or let user pick date, but brief said
            // "Hora" mostly)
            // Let's assume a default date for now or just "Amanhã" text logic
            String date = "Amanhã";

            // Save to DB
            Appointment newAppt = new Appointment("Consulta Geral", date, time, false);
            appointmentsViewModel.insert(newAppt);

            binding.buttonBookAppointment.setText("Consulta marcada: " + time);
            Toast.makeText(getContext(), "Consulta marcada para " + time, Toast.LENGTH_SHORT).show();

        }, hour, minute, true);

        mTimePicker.setTitle("Selecione a hora");
        mTimePicker.show();
    }

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