package com.example.cuida.ui.medication;

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 androidx.recyclerview.widget.LinearLayoutManager;
import com.example.cuida.data.model.Medication;
import com.example.cuida.databinding.FragmentMedicationBinding;

public class MedicationFragment extends Fragment {

    private FragmentMedicationBinding binding;
    private MedicationViewModel medicationViewModel;

    public View onCreateView(@NonNull LayoutInflater inflater,
            ViewGroup container, Bundle savedInstanceState) {
        medicationViewModel = new ViewModelProvider(this).get(MedicationViewModel.class);

        binding = FragmentMedicationBinding.inflate(inflater, container, false);

        MedicationAdapter adapter = new MedicationAdapter(new MedicationAdapter.OnItemClickListener() {
            @Override
            public void onCheckClick(Medication medication) {
                medicationViewModel.update(medication);
            }

            @Override
            public void onItemClick(Medication medication) {
                showMedicationDialog(medication);
            }
        });

        binding.recyclerMedication.setLayoutManager(new LinearLayoutManager(getContext()));
        binding.recyclerMedication.setAdapter(adapter);

        medicationViewModel.getAllMedications().observe(getViewLifecycleOwner(), medications -> {
            adapter.setMedications(medications);
            
            if (medications != null && !medications.isEmpty()) {
                binding.recyclerMedication.setVisibility(View.VISIBLE);
                binding.textEmptyMedications.setVisibility(View.GONE);
            } else {
                binding.recyclerMedication.setVisibility(View.GONE);
                binding.textEmptyMedications.setVisibility(View.VISIBLE);
            }
        });

        binding.fabAddMedication.setOnClickListener(v -> showMedicationDialog(null));

        return binding.getRoot();
    }

    private void showMedicationDialog(Medication medication) {
        MedicationDialog dialog = new MedicationDialog();
        dialog.setMedicationToEdit(medication);
        dialog.setListener(medicationToSave -> {
            // If it's an edit, cancel old alarms first
            if (medication != null && medication.time != null) {
                String[] oldTimes = medication.time.split(",\\s*");
                for (String t : oldTimes) {
                    if (t.isEmpty()) continue;
                    try {
                        int oldId = (medication.name + t).hashCode();
                        com.example.cuida.utils.AlarmScheduler.cancelAlarm(requireContext(), oldId);
                    } catch (Exception e) {}
                }
            }

            if (medication == null) {
                medicationViewModel.insert(medicationToSave);
            } else {
                medicationViewModel.update(medicationToSave);
            }

            String[] times = medicationToSave.time.split(",\\s*");
            for (String t : times) {
                if (t.isEmpty()) continue;
                try {
                    String[] timeParts = t.split(":");
                    int hour = Integer.parseInt(timeParts[0]);
                    int minute = Integer.parseInt(timeParts[1]);

                    java.util.Calendar calendar = java.util.Calendar.getInstance();
                    calendar.set(java.util.Calendar.HOUR_OF_DAY, hour);
                    calendar.set(java.util.Calendar.MINUTE, minute);
                    calendar.set(java.util.Calendar.SECOND, 0);

                    if (calendar.getTimeInMillis() <= System.currentTimeMillis()) {
                        calendar.add(java.util.Calendar.DAY_OF_YEAR, 1);
                    }

                    String title = "Hora do Medicamento";
                    String msg = "É hora de tomar: " + medicationToSave.name + " (" + medicationToSave.dosage + ")";
                    
                    int alarmId = (medicationToSave.name + t).hashCode();
                    
                    com.example.cuida.utils.AlarmScheduler.scheduleAlarm(
                            requireContext(),
                            calendar.getTimeInMillis(),
                            title,
                            msg,
                            alarmId);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            dialog.dismiss();
        });
        
        dialog.setDeleteListener(medicationToDelete -> {
            medicationViewModel.delete(medicationToDelete);
            
            // Cancel all alarms for this medication
            if (medicationToDelete.time != null) {
                String[] times = medicationToDelete.time.split(",\\s*");
                for (String t : times) {
                    if (t.isEmpty()) continue;
                    try {
                        int alarmId = (medicationToDelete.name + t).hashCode();
                        com.example.cuida.utils.AlarmScheduler.cancelAlarm(requireContext(), alarmId);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        
        dialog.show(getParentFragmentManager(), "MedicationDialog");
    }

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