package com.example.cuida.ui.medication;

import android.app.Dialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.DialogFragment;
import com.example.cuida.R;
import com.example.cuida.data.model.Medication;
import java.util.Calendar;
import java.util.Locale;

public class MedicationDialog extends DialogFragment {

    private EditText editName, editNotes;
    private android.widget.CheckBox checkOral, checkTopical, checkInhalatory;
    private TextView textTime;
    private Medication medicationToEdit;
    private OnMedicationSaveListener listener;

    public interface OnMedicationSaveListener {
        void onSave(Medication medication);
    }

    public void setListener(OnMedicationSaveListener listener) {
        this.listener = listener;
    }

    public void setMedicationToEdit(Medication medication) {
        this.medicationToEdit = medication;
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
        LayoutInflater inflater = requireActivity().getLayoutInflater();
        View view = inflater.inflate(R.layout.dialog_add_medication, null);

        editName = view.findViewById(R.id.edit_med_name);
        editNotes = view.findViewById(R.id.edit_med_notes);
        textTime = view.findViewById(R.id.text_med_time);

        checkOral = view.findViewById(R.id.checkbox_oral);
        checkTopical = view.findViewById(R.id.checkbox_topical);
        checkInhalatory = view.findViewById(R.id.checkbox_inhalatory);

        // Set up TimePicker
        textTime.setOnClickListener(v -> showTimePicker());

        if (medicationToEdit != null) {
            editName.setText(medicationToEdit.name);
            editNotes.setText(medicationToEdit.notes);
            textTime.setText(medicationToEdit.time);

            // Parse dosage string to set checkboxes
            String dosage = medicationToEdit.dosage;
            if (dosage != null) {
                checkOral.setChecked(dosage.contains("Oral"));
                checkTopical.setChecked(dosage.contains("Tópica"));
                checkInhalatory.setChecked(dosage.contains("Inalatória"));
            }

            builder.setTitle("Editar Medicamento");
        } else {
            builder.setTitle("Adicionar Medicamento");
            // Default time to current time
            Calendar cal = Calendar.getInstance();
            updateTimeLabel(cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE));
        }

        builder.setView(view)
                .setPositiveButton("Guardar", (dialog, id) -> {
                    String name = editName.getText().toString();
                    String notes = editNotes.getText().toString();
                    String time = textTime.getText().toString();

                    StringBuilder dosageBuilder = new StringBuilder();
                    if (checkOral.isChecked())
                        dosageBuilder.append("Via Oral, ");
                    if (checkTopical.isChecked())
                        dosageBuilder.append("Via Tópica, ");
                    if (checkInhalatory.isChecked())
                        dosageBuilder.append("Via Inalatória, ");

                    String dosage = dosageBuilder.toString();
                    if (dosage.endsWith(", ")) {
                        dosage = dosage.substring(0, dosage.length() - 2);
                    } else if (dosage.isEmpty()) {
                        dosage = "Via não especificada";
                    }

                    if (medicationToEdit != null) {
                        medicationToEdit.name = name;
                        medicationToEdit.dosage = dosage;
                        medicationToEdit.notes = notes;
                        medicationToEdit.time = time;
                        if (listener != null)
                            listener.onSave(medicationToEdit);
                    } else {
                        Medication newMed = new Medication(name, time, dosage, notes);
                        if (listener != null)
                            listener.onSave(newMed);
                    }
                })
                .setNegativeButton("Cancelar", (dialog, id) -> dismiss());

        return builder.create();
    }

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

        if (medicationToEdit != null) {
            try {
                String[] parts = medicationToEdit.time.split(":");
                hour = Integer.parseInt(parts[0]);
                minute = Integer.parseInt(parts[1]);
            } catch (Exception e) {
                // Use current time if parsing fails
            }
        }

        TimePickerDialog timePickerDialog = new TimePickerDialog(getContext(),
                (view, hourOfDay, minute1) -> updateTimeLabel(hourOfDay, minute1),
                hour, minute, true);
        timePickerDialog.show();
    }

    private void updateTimeLabel(int hourOfDay, int minute) {
        String time = String.format(Locale.getDefault(), "%02d:%02d", hourOfDay, minute);
        textTime.setText(time);
    }
}
