package com.example.cuida.ui.medication;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.cuida.R;
import com.example.cuida.data.model.Medication;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class MedicationAdapter extends RecyclerView.Adapter<MedicationAdapter.MedicationViewHolder> {

    private List<Medication> medicationList = new ArrayList<>();
    private final OnItemClickListener listener;

    public interface OnItemClickListener {
        void onCheckClick(Medication medication);

        void onItemClick(Medication medication);
    }

    public MedicationAdapter(OnItemClickListener listener) {
        this.listener = listener;
    }

    public void setMedications(List<Medication> medications) {
        this.medicationList = medications;
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public MedicationViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_medication, parent, false);
        return new MedicationViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull MedicationViewHolder holder, int position) {
        Medication medication = medicationList.get(position);
        holder.textName.setText(medication.name);
        holder.textDosage.setText(medication.dosage);
        holder.textTime.setText(medication.time);
        holder.textNotes.setText(medication.notes);

        // Lógica para resetar o "certo" a cada novo horário
        boolean wasTakenForDose = wasTakenForCurrentDose(medication);

        // Remove listener temporarily to avoid triggering it during bind
        holder.checkBoxTaken.setOnCheckedChangeListener(null);
        holder.checkBoxTaken.setChecked(wasTakenForDose);

        holder.checkBoxTaken.setOnCheckedChangeListener((buttonView, isChecked) -> {
            medication.isTaken = isChecked;
            if (isChecked) {
                medication.lastTakenTimestamp = System.currentTimeMillis();
            } else {
                medication.lastTakenTimestamp = 0;
            }
            listener.onCheckClick(medication);
        });
    }

    private boolean wasTakenForCurrentDose(Medication med) {
        if (!med.isTaken || med.lastTakenTimestamp == 0 || med.time == null) return false;

        try {
            String[] scheduleTimes = med.time.split(",\\s*");
            java.util.Calendar now = java.util.Calendar.getInstance();
            long mostRecentScheduleToday = 0;

            for (String t : scheduleTimes) {
                String[] parts = t.split(":");
                if (parts.length != 2) continue;

                java.util.Calendar sched = java.util.Calendar.getInstance();
                sched.set(java.util.Calendar.HOUR_OF_DAY, Integer.parseInt(parts[0]));
                sched.set(java.util.Calendar.MINUTE, Integer.parseInt(parts[1]));
                sched.set(java.util.Calendar.SECOND, 0);
                sched.set(java.util.Calendar.MILLISECOND, 0);

                // Se este horário já passou hoje
                if (sched.before(now)) {
                    if (sched.getTimeInMillis() > mostRecentScheduleToday) {
                        mostRecentScheduleToday = sched.getTimeInMillis();
                    }
                }
            }

            // Se ainda nenhum horário passou hoje, verificamos se tomou ontem/antes
            if (mostRecentScheduleToday == 0) {
                // Opcional: resetar ao início do dia
                java.util.Calendar startOfDay = java.util.Calendar.getInstance();
                startOfDay.set(java.util.Calendar.HOUR_OF_DAY, 0);
                startOfDay.set(java.util.Calendar.MINUTE, 0);
                return med.lastTakenTimestamp > startOfDay.getTimeInMillis();
            }

            // O "certo" só fica se tomou DEPOIS do horário agendado que passou
            return med.lastTakenTimestamp >= mostRecentScheduleToday;

        } catch (Exception e) {
            return med.isTaken;
        }
    }

    @Override
    public int getItemCount() {
        return medicationList.size();
    }

    public class MedicationViewHolder extends RecyclerView.ViewHolder {
        TextView textName, textDosage, textTime, textNotes;
        CheckBox checkBoxTaken;

        public MedicationViewHolder(@NonNull View itemView) {
            super(itemView);
            textName = itemView.findViewById(R.id.text_med_name);
            textDosage = itemView.findViewById(R.id.text_med_dosage);
            textTime = itemView.findViewById(R.id.text_med_time);
            textNotes = itemView.findViewById(R.id.text_med_notes);
            checkBoxTaken = itemView.findViewById(R.id.checkbox_taken);

            itemView.setOnClickListener(v -> {
                int position = getAdapterPosition();
                if (listener != null && position != RecyclerView.NO_POSITION) {
                    listener.onItemClick(medicationList.get(position));
                }
            });
        }
    }
}
