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);
        });

        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 (medication == null) {
                medicationViewModel.insert(medicationToSave);
            } else {
                medicationViewModel.update(medicationToSave);
            }
            dialog.dismiss();
        });
        dialog.show(getParentFragmentManager(), "MedicationDialog");
    }

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