package com.example.bem;

import android.Manifest;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.app.AppCompatDelegate;
import androidx.appcompat.widget.SwitchCompat;
import androidx.core.content.ContextCompat;

import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QueryDocumentSnapshot;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

public class MainActivity extends AppCompatActivity {

    private enum Tab {
        ALARMS,
        REMINDERS,
        GUARDIANS,
        CALENDAR
    }

    private FrameLayout tabContainer;
    private LinearLayout tabAlarms;
    private LinearLayout tabReminders;
    private LinearLayout tabGuardians;
    private LinearLayout tabCalendar;
    private ImageView iconAlarms;
    private ImageView iconReminders;
    private ImageView iconGuardians;
    private ImageView iconCalendar;
    private TextView textAlarms;
    private TextView textReminders;
    private TextView textGuardians;
    private TextView textCalendar;

    private LayoutInflater inflater;
    private View alarmsView;
    private View remindersView;
    private View guardiansView;
    private View calendarView;
    private LinearLayout alarmListContainer;
    private final List<AlarmItem> alarms = new ArrayList<>();
    private Tab currentTab = null;
    private FirebaseAuth mAuth;
    private FirebaseFirestore db;
    private SharedPreferences prefs;
    private static final String PREF_DARK_MODE = "dark_mode";
    private int editingAlarmIndex = -1;
    private String currentUserId = null;
    private boolean isGuardian = false;

    private final ActivityResultLauncher<String> notificationPermissionLauncher = registerForActivityResult(
            new ActivityResultContracts.RequestPermission(), isGranted -> {
                if (isGranted) {
                    Toast.makeText(this, "Permissão de notificações concedida!", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(this, "Permissão negada. Alarmes podem não tocar.", Toast.LENGTH_LONG).show();
                }
            });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mAuth = FirebaseAuth.getInstance();
        db = FirebaseFirestore.getInstance();

        FirebaseUser currentUser = mAuth.getCurrentUser();
        if (currentUser == null) {
            redirectToLogin();
            return;
        }

        currentUserId = currentUser.getUid();
        prefs = getSharedPreferences("app_prefs", MODE_PRIVATE);
        applyThemeFromPrefs();

        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        inflater = LayoutInflater.from(this);

        String userType = prefs.getString("user_type", "user");
        isGuardian = "guardian".equals(userType);

        tabContainer = findViewById(R.id.tabContainer);
        tabAlarms = findViewById(R.id.tabAlarms);
        tabReminders = findViewById(R.id.tabReminders);
        tabGuardians = findViewById(R.id.tabGuardians);
        tabCalendar = findViewById(R.id.tabCalendar);

        iconAlarms = findViewById(R.id.iconAlarms);
        iconReminders = findViewById(R.id.iconReminders);
        iconGuardians = findViewById(R.id.iconGuardians);
        iconCalendar = findViewById(R.id.iconCalendar);

        textAlarms = findViewById(R.id.textAlarms);
        textReminders = findViewById(R.id.textReminders);
        textGuardians = findViewById(R.id.textGuardians);
        textCalendar = findViewById(R.id.textCalendar);

        ImageView profileButton = findViewById(R.id.profileButton);

        tabAlarms.setOnClickListener(v -> switchTab(Tab.ALARMS));
        tabReminders.setOnClickListener(v -> switchTab(Tab.REMINDERS));
        tabGuardians.setOnClickListener(v -> handleGuardianTabClick());
        tabCalendar.setOnClickListener(v -> switchTab(Tab.CALENDAR));
        profileButton.setOnClickListener(v -> showProfileMenu());

        requestNotificationPermissions();
        applyUserModeLayout();
        loadAlarmsFromFirestore();
        showIntroDialogIfNeeded();
    }

    private void applyUserModeLayout() {
        if (isGuardian) {
            tabAlarms.setVisibility(View.GONE);
            tabReminders.setVisibility(View.GONE);
            tabCalendar.setVisibility(View.VISIBLE);
            switchTab(Tab.GUARDIANS);
        } else {
            tabAlarms.setVisibility(View.VISIBLE);
            tabReminders.setVisibility(View.VISIBLE);
            tabCalendar.setVisibility(View.GONE);
            switchTab(Tab.ALARMS);
        }
    }

    private void redirectToLogin() {
        Intent intent = new Intent(this, LoginActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
        finish();
    }

    private void requestNotificationPermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
                notificationPermissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS);
            }
        }
    }

    private void handleGuardianTabClick() {
        if (isGuardian) {
            switchTab(Tab.GUARDIANS);
        } else {
             db.collection("users").document(currentUserId).get().addOnSuccessListener(documentSnapshot -> {
                if (documentSnapshot.exists() && documentSnapshot.contains("guardianId")) {
                    Toast.makeText(this, "Já tem um responsável associado.", Toast.LENGTH_SHORT).show();
                     switchTab(Tab.GUARDIANS);
                } else {
                    new AlertDialog.Builder(this)
                        .setTitle("Controle Parental")
                        .setMessage("Ainda não tem um responsável associado. Deseja gerar um código de convite para adicionar um?")
                        .setPositiveButton("Gerar Código", (dialog, which) -> {
                            Intent intent = new Intent(MainActivity.this, GenerateCodeActivity.class);
                            startActivity(intent);
                        })
                        .setNegativeButton("Agora Não", null)
                        .show();
                }
            });
        }
    }

    private void showProfileMenu() {
        View dialogView = inflater.inflate(R.layout.dialog_profile, null);
        AlertDialog dialog = new AlertDialog.Builder(this)
                .setView(dialogView)
                .create();

        if (dialog.getWindow() != null) {
            dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        }

        TextView textName = dialogView.findViewById(R.id.textProfileName);
        TextView textEmail = dialogView.findViewById(R.id.textProfileEmail);
        LinearLayout btnTheme = dialogView.findViewById(R.id.btnProfileTheme);
        LinearLayout btnSupport = dialogView.findViewById(R.id.btnProfileSupport);
        LinearLayout btnExitGuardian = dialogView.findViewById(R.id.btnProfileExitGuardian);
        LinearLayout btnLogout = dialogView.findViewById(R.id.btnProfileLogout);
        Button btnClose = dialogView.findViewById(R.id.btnProfileClose);

        String name = prefs.getString("user_name", "Utilizador");
        FirebaseUser user = mAuth.getCurrentUser();
        String email = user != null ? user.getEmail() : "Não disponível";

        textName.setText(name);
        textEmail.setText(email);

        btnTheme.setOnClickListener(v -> {
            dialog.dismiss();
            toggleDarkMode();
        });

        btnSupport.setOnClickListener(v -> {
            dialog.dismiss();
            openSupportEmail();
        });

        if (isGuardian) {
            btnExitGuardian.setVisibility(View.VISIBLE);
            btnExitGuardian.setOnClickListener(v -> {
                dialog.dismiss();
                exitGuardianMode();
            });
        } else {
            btnExitGuardian.setVisibility(View.GONE);
        }

        btnLogout.setOnClickListener(v -> {
            dialog.dismiss();
            logout();
        });

        btnClose.setOnClickListener(v -> dialog.dismiss());

        dialog.show();
    }

    private void exitGuardianMode() {
        prefs.edit().putString("user_type", "user").apply();
        Intent intent = new Intent(this, InviteCodeActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
        finish();
    }

    private void toggleDarkMode() {
        boolean isDarkMode = prefs.getBoolean(PREF_DARK_MODE, false);
        prefs.edit().putBoolean(PREF_DARK_MODE, !isDarkMode).apply();
        recreate();
    }

    private void openSupportEmail() {
        Intent intent = new Intent(Intent.ACTION_SENDTO);
        intent.setData(Uri.parse("mailto:support@bempap.com"));
        intent.putExtra(Intent.EXTRA_SUBJECT, "Suporte App Bem+");
        try {
            startActivity(intent);
        } catch (Exception e) {
            Toast.makeText(this, "Nenhuma app de email encontrada.", Toast.LENGTH_SHORT).show();
        }
    }

    private void logout() {
        mAuth.signOut();
        redirectToLogin();
    }

    private void applyThemeFromPrefs() {
        if (prefs.getBoolean(PREF_DARK_MODE, false)) {
            AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
        } else {
            AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
        }
    }

    private void switchTab(Tab tab) {
        if (tab == currentTab) return;
        currentTab = tab;

        View oldContent = tabContainer.getChildCount() > 0 ? tabContainer.getChildAt(0) : null;
        if (oldContent != null) {
            oldContent.animate().alpha(0f).setDuration(150).withEndAction(() -> {
                tabContainer.removeAllViews();
                loadAndShowTab(tab);
            }).start();
        } else {
            loadAndShowTab(tab);
        }
    }

    private void loadAndShowTab(Tab tab) {
        View content;
        switch (tab) {
            case REMINDERS:
                if (remindersView == null) remindersView = inflater.inflate(R.layout.layout_tab_reminders, tabContainer, false);
                content = remindersView;
                break;
            case GUARDIANS:
                if (guardiansView == null) guardiansView = inflater.inflate(R.layout.layout_tab_guardians, tabContainer, false);
                loadGuardianData(guardiansView);
                content = guardiansView;
                break;
            case CALENDAR:
                if (calendarView == null) calendarView = inflater.inflate(R.layout.layout_tab_calendar, tabContainer, false);
                setupCalendar(calendarView);
                content = calendarView;
                break;
            case ALARMS:
            default:
                if (alarmsView == null) alarmsView = inflater.inflate(R.layout.layout_tab_alarms, tabContainer, false);
                Button addAlarm = alarmsView.findViewById(R.id.btnAddAlarm);
                alarmListContainer = alarmsView.findViewById(R.id.alarmListContainer);
                if (addAlarm != null) addAlarm.setOnClickListener(v -> showAddAlarmDialog());
                renderAlarms();
                content = alarmsView;
                break;
        }

        content.setAlpha(0f);
        tabContainer.addView(content);
        content.animate().alpha(1f).setDuration(120).start();
        updateTabHighlight(tab);
    }

    private void setupCalendar(View view) {
        if (view == null) return;
        LinearLayout calendarGrid = view.findViewById(R.id.calendarGrid);
        TextView monthTitle = view.findViewById(R.id.textMonthTitle);
        LinearLayout legendContainer = view.findViewById(R.id.legendContainer);

        if (calendarGrid == null || monthTitle == null || legendContainer == null) return;

        calendarGrid.removeAllViews();
        legendContainer.removeAllViews();

        Calendar calendar = Calendar.getInstance();
        int currentDay = calendar.get(Calendar.DAY_OF_MONTH);
        int currentMonth = calendar.get(Calendar.MONTH);

        String[] months = { "Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro" };
        monthTitle.setText(String.format(Locale.getDefault(), "%s %d", months[currentMonth], calendar.get(Calendar.YEAR)));

        int[] dotColors = { ContextCompat.getColor(this, R.color.primary), ContextCompat.getColor(this, R.color.guardian_purple_end), ContextCompat.getColor(this, R.color.delete), 0xFFFFA500, 0xFF00C853 };
        Map<String, Integer> medColors = new HashMap<>();
        int colorIndex = 0;
        for (AlarmItem alarm : alarms) {
            if (!medColors.containsKey(alarm.title)) {
                int color = dotColors[colorIndex % dotColors.length];
                medColors.put(alarm.title, color);
                colorIndex++;
                TextView legendItem = new TextView(this);
                legendItem.setText(String.format(Locale.getDefault(), "• %s", alarm.title));
                legendItem.setTextColor(color);
                legendItem.setTextSize(14);
                legendItem.setPadding(0, 0, 0, 8);
                legendContainer.addView(legendItem);
            }
        }

        calendar.set(Calendar.DAY_OF_MONTH, 1);
        int firstDayOfWeek = calendar.get(Calendar.DAY_OF_WEEK) - 1;
        int daysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);

        SharedPreferences logPrefs = getSharedPreferences("medication_log", MODE_PRIVATE);
        java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyyMMdd", Locale.getDefault());
        LinearLayout currentWeekRow = new LinearLayout(this);
        currentWeekRow.setOrientation(LinearLayout.HORIZONTAL);
        calendarGrid.addView(currentWeekRow);

        for (int i = 0; i < firstDayOfWeek; i++) {
            View empty = new View(this);
            empty.setLayoutParams(new LinearLayout.LayoutParams(0, 50, 1.0f));
            currentWeekRow.addView(empty);
        }

        int dayOfWeekCounter = firstDayOfWeek;
        for (int day = 1; day <= daysInMonth; day++) {
            if (dayOfWeekCounter == 0) {
                currentWeekRow = new LinearLayout(this);
                currentWeekRow.setOrientation(LinearLayout.HORIZONTAL);
                calendarGrid.addView(currentWeekRow);
            }
            View dayCell = inflater.inflate(R.layout.item_calendar_day, currentWeekRow, false);
            TextView numText = dayCell.findViewById(R.id.textDayNumber);
            LinearLayout dots = dayCell.findViewById(R.id.dotsContainer);
            numText.setText(String.valueOf(day));

            if (day == currentDay) {
                numText.setBackground(ContextCompat.getDrawable(this, R.drawable.bg_calendar_day_selected));
                numText.setTextColor(ContextCompat.getColor(this, R.color.primary));
            }

            calendar.set(Calendar.DAY_OF_MONTH, day);
            String dateKey = sdf.format(calendar.getTime());
            for (AlarmItem alarm : alarms) {
                String key = "med_" + alarm.title.replaceAll("\\s+", "_") + "_" + dateKey;
                if (logPrefs.getBoolean(key + "_taken", false)) {
                    View dot = new View(this);
                    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(12, 12);
                    params.setMargins(2, 0, 2, 0);
                    dot.setLayoutParams(params);
                    dot.setBackground(ContextCompat.getDrawable(this, R.drawable.bg_dot));
                    Integer color = medColors.get(alarm.title);
                    if (color != null && dot.getBackground() != null) {
                        dot.getBackground().setTint(color);
                    }
                    dots.addView(dot);
                }
            }
            currentWeekRow.addView(dayCell);
            dayOfWeekCounter = (dayOfWeekCounter + 1) % 7;
        }
        while (dayOfWeekCounter != 0 && dayOfWeekCounter < 7) {
            View empty = new View(this);
            empty.setLayoutParams(new LinearLayout.LayoutParams(0, 50, 1.0f));
            currentWeekRow.addView(empty);
            dayOfWeekCounter++;
        }
    }

    private void updateTabHighlight(Tab tab) {
        resetTab(tabAlarms, iconAlarms, textAlarms);
        resetTab(tabReminders, iconReminders, textReminders);
        resetTab(tabGuardians, iconGuardians, textGuardians);
        resetTab(tabCalendar, iconCalendar, textCalendar);
        switch (tab) {
            case ALARMS: highlightTab(tabAlarms, iconAlarms, textAlarms); break;
            case REMINDERS: highlightTab(tabReminders, iconReminders, textReminders); break;
            case GUARDIANS: highlightTab(tabGuardians, iconGuardians, textGuardians); break;
            case CALENDAR: highlightTab(tabCalendar, iconCalendar, textCalendar); break;
        }
    }

    private void highlightTab(LinearLayout layout, ImageView icon, TextView text) {
        layout.setBackground(ContextCompat.getDrawable(this, R.drawable.bg_tab_active));
        icon.setColorFilter(ContextCompat.getColor(this, R.color.primary));
        text.setTextColor(ContextCompat.getColor(this, R.color.primary));
    }

    private void resetTab(LinearLayout layout, ImageView icon, TextView text) {
        layout.setBackground(null);
        int neutral = ContextCompat.getColor(this, R.color.neutral_medium);
        icon.setColorFilter(neutral);
        text.setTextColor(neutral);
    }

    private void renderAlarms() {
        if (alarmListContainer == null) return;
        alarmListContainer.removeAllViews();
        if (alarms.isEmpty()) {
            TextView empty = new TextView(this);
            empty.setText(R.string.no_alarms_message);
            empty.setTextColor(ContextCompat.getColor(this, R.color.neutral_medium));
            empty.setPadding(0, 24, 0, 24);
            alarmListContainer.addView(empty);
            return;
        }
        for (int i = 0; i < alarms.size(); i++) {
            final int index = i;
            AlarmItem item = alarms.get(i);
            View card = inflater.inflate(R.layout.item_alarm_card, alarmListContainer, false);
            TextView title = card.findViewById(R.id.textAlarmTitle);
            TextView time = card.findViewById(R.id.textAlarmTime);
            TextView days = card.findViewById(R.id.textAlarmDays);
            SwitchCompat toggle = card.findViewById(R.id.switchAlarm);
            ImageButton edit = card.findViewById(R.id.buttonEditAlarm);
            ImageButton delete = card.findViewById(R.id.buttonDeleteAlarm);
            Button confirmBtn = card.findViewById(R.id.btnConfirmMedication);

            title.setText(item.title);
            time.setText(item.time);
            days.setText(item.days);
            toggle.setChecked(item.enabled);

            if (item.takenToday) {
                confirmBtn.setText(R.string.taken_confirmed);
                confirmBtn.setBackgroundColor(ContextCompat.getColor(this, R.color.neutral_medium));
                confirmBtn.setEnabled(false);
            } else {
                confirmBtn.setText(R.string.confirm_medication);
                confirmBtn.setBackground(ContextCompat.getDrawable(this, R.drawable.bg_new_button));
                confirmBtn.setEnabled(true);
            }

            confirmBtn.setOnClickListener(v -> {
                item.takenToday = true;
                item.lastTakenTimestamp = System.currentTimeMillis();
                saveMedicationConfirmation(item);
                renderAlarms();
                showConfirmationDialog(item);
            });

            toggle.setOnCheckedChangeListener((buttonView, isChecked) -> {
                item.enabled = isChecked;
                updateAlarmInFirestore(item);
            });

            edit.setOnClickListener(v -> showEditAlarmDialog(item, index));

            delete.setOnClickListener(v -> new AlertDialog.Builder(this)
                    .setTitle("Remover Alarme")
                    .setMessage("Tem certeza que deseja remover \"" + item.title + "\"?")
                    .setPositiveButton("Remover", (dialog, which) -> deleteAlarmFromFirestore(item, index))
                    .setNegativeButton("Cancelar", null).show());

            alarmListContainer.addView(card);
        }
    }

    private void showConfirmationDialog(AlarmItem item) {
        java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("HH:mm", Locale.getDefault());
        String timeStr = sdf.format(new java.util.Date(item.lastTakenTimestamp));
        new AlertDialog.Builder(this)
                .setTitle("✓ Medicamento Confirmado")
                .setMessage("Confirmou que tomou:\n\n" + "💊 " + item.title + "\n" + "🕐 Às " + timeStr + "\n\n" + "O responsável será notificado automaticamente.")
                .setPositiveButton("OK", null)
                .show();
        Toast.makeText(this, "Responsável notificado!", Toast.LENGTH_LONG).show();
    }

    private void saveMedicationConfirmation(AlarmItem item) {
        SharedPreferences confirmPrefs = getSharedPreferences("medication_log", MODE_PRIVATE);
        String key = "med_" + item.title.replaceAll("\\s+", "_") + "_" + new java.text.SimpleDateFormat("yyyyMMdd", Locale.getDefault()).format(new java.util.Date());
        confirmPrefs.edit().putLong(key, item.lastTakenTimestamp).putBoolean(key + "_taken", true).putString(key + "_title", item.title).apply();
    }

    private void loadGuardianData(View guardiansView) {
        SharedPreferences confirmPrefs = getSharedPreferences("medication_log", MODE_PRIVATE);
        java.text.SimpleDateFormat dateFormat = new java.text.SimpleDateFormat("yyyyMMdd", Locale.getDefault());
        String today = dateFormat.format(new java.util.Date());
        
        // Match IDs with layout_tab_guardians.xml
        TextView patientName = guardiansView.findViewById(R.id.textPatientName);
        TextView patientStatus = guardiansView.findViewById(R.id.textPatientStatus);
        LinearLayout medicationStatusList = guardiansView.findViewById(R.id.medicationStatusList);
        
        if (patientName != null) {
            String name = prefs.getString("user_name", "Utilizador");
            patientName.setText(name);
        }
        if (patientStatus != null) patientStatus.setText(R.string.online_updated_now);

        if (medicationStatusList != null) {
            medicationStatusList.removeAllViews();
            for (AlarmItem alarm : alarms) {
                String key = "med_" + alarm.title.replaceAll("\\s+", "_") + "_" + today;
                boolean taken = confirmPrefs.getBoolean(key + "_taken", false);
                long timestamp = confirmPrefs.getLong(key, 0);

                View statusCard = inflater.inflate(R.layout.item_alarm_card, medicationStatusList, false);
                TextView titleView = statusCard.findViewById(R.id.textAlarmTitle);
                TextView timeView = statusCard.findViewById(R.id.textAlarmTime);
                TextView daysView = statusCard.findViewById(R.id.textAlarmDays);
                statusCard.findViewById(R.id.btnConfirmMedication).setVisibility(View.GONE);
                statusCard.findViewById(R.id.switchAlarm).setVisibility(View.GONE);
                statusCard.findViewById(R.id.buttonDeleteAlarm).setVisibility(View.GONE);
                statusCard.findViewById(R.id.buttonEditAlarm).setVisibility(View.GONE);

                titleView.setText(alarm.title);
                timeView.setText(alarm.time);

                if (taken) {
                    String takenTime = new java.text.SimpleDateFormat("HH:mm", Locale.getDefault()).format(new java.util.Date(timestamp));
                    daysView.setText(String.format(Locale.getDefault(), "✓ Tomado às %s", takenTime));
                    daysView.setTextColor(ContextCompat.getColor(this, R.color.primary));
                } else {
                    daysView.setText(R.string.pending_status);
                    daysView.setTextColor(ContextCompat.getColor(this, R.color.delete));
                }
                medicationStatusList.addView(statusCard);
            }
        }
        
        // Add "Add Guardian" logic if needed
        View btnAddGuardian = guardiansView.findViewById(R.id.btnAddGuardian);
        if (btnAddGuardian != null) {
            btnAddGuardian.setOnClickListener(v -> {
                Intent intent = new Intent(this, GenerateCodeActivity.class);
                startActivity(intent);
            });
        }
    }

    private void showAddAlarmDialog() {
        View dialogView = inflater.inflate(R.layout.dialog_add_alarm, null, false);
        EditText titleInput = dialogView.findViewById(R.id.inputAlarmTitle);
        TextView timeDisplay = dialogView.findViewById(R.id.textSelectedTime);
        EditText detailsInput = dialogView.findViewById(R.id.inputAlarmDetails);

        final int[] selectedHour = { 8 };
        final int[] selectedMinute = { 0 };

        timeDisplay.setText(String.format(Locale.getDefault(), "%02d:%02d", selectedHour[0], selectedMinute[0]));
        timeDisplay.setTextColor(ContextCompat.getColor(this, R.color.neutral_dark));

        ((View) timeDisplay.getParent()).setOnClickListener(v -> {
            android.app.TimePickerDialog picker = new android.app.TimePickerDialog(this,
                    (view, hourOfDay, minute) -> {
                        selectedHour[0] = hourOfDay;
                        selectedMinute[0] = minute;
                        timeDisplay.setText(String.format(Locale.getDefault(), "%02d:%02d", hourOfDay, minute));
                    }, selectedHour[0], selectedMinute[0], true);
            picker.setTitle("Escolha o horário");
            picker.show();
        });

        AlertDialog dialog = new AlertDialog.Builder(this).setView(dialogView).setPositiveButton("Guardar", null).setNegativeButton("Cancelar", null).create();
        dialog.setOnShowListener(dialogInterface -> {
            Button positiveButton = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
            positiveButton.setOnClickListener(v -> {
                String title = titleInput.getText().toString().trim();
                if (TextUtils.isEmpty(title)) {
                    titleInput.setError("Insira o nome do medicamento");
                    return;
                }
                String details = detailsInput.getText().toString().trim();
                String timeFormatted = String.format(Locale.getDefault(), "%02d:%02d", selectedHour[0], selectedMinute[0]);

                AlarmItem newAlarm = new AlarmItem(title, timeFormatted + " • " + details, "Seg • Ter • Qua • Qui • Sex", true);
                newAlarm.hour = selectedHour[0];
                newAlarm.minute = selectedMinute[0];

                saveAlarmInFirestore(newAlarm);
                dialog.dismiss();
            });
        });
        dialog.show();
    }

    private void showEditAlarmDialog(AlarmItem item, int index) {
        editingAlarmIndex = index;
        String[] options = { "⏰ Alterar horário", "📝 Editar título", "📅 Alterar dias" };
        new AlertDialog.Builder(this).setTitle("Editar: " + item.title).setItems(options, (dialog, which) -> {
            switch (which) {
                case 0: showChangeTimeDialog(item); break;
                case 1: showEditTitleDialog(item); break;
                case 2: showEditDaysDialog(item); break;
            }
        }).setNegativeButton("Fechar", null).show();
    }

    private void showEditDaysDialog(AlarmItem item) {
        String[] days = {"Segunda", "Terça", "Quarta", "Quinta", "Sexta", "Sábado", "Domingo"};
        boolean[] checked = new boolean[7];
        if (item.days != null) {
            if (item.days.contains("Seg")) checked[0] = true;
            if (item.days.contains("Ter")) checked[1] = true;
            if (item.days.contains("Qua")) checked[2] = true;
            if (item.days.contains("Qui")) checked[3] = true;
            if (item.days.contains("Sex")) checked[4] = true;
            if (item.days.contains("Sáb")) checked[5] = true;
            if (item.days.contains("Dom")) checked[6] = true;
        }

        new AlertDialog.Builder(this)
                .setTitle("Escolher dias")
                .setMultiChoiceItems(days, checked, (dialog, which, isChecked) -> checked[which] = isChecked)
                .setPositiveButton("OK", (dialog, which) -> {
                    StringBuilder sb = new StringBuilder();
                    String[] shorts = {"Seg", "Ter", "Qua", "Qui", "Sex", "Sáb", "Dom"};
                    for (int i = 0; i < 7; i++) {
                        if (checked[i]) {
                            if (sb.length() > 0) sb.append(" • ");
                            sb.append(shorts[i]);
                        }
                    }
                    if (sb.length() == 0) sb.append("Nenhum dia");
                    item.days = sb.toString();
                    updateAlarmInFirestore(item);
                })
                .setNegativeButton("Cancelar", null)
                .show();
    }

    private void showChangeTimeDialog(AlarmItem item) {
        new android.app.TimePickerDialog(this, (view, hourOfDay, minute) -> {
            item.hour = hourOfDay;
            item.minute = minute;
            String details = item.time.contains("•") ? item.time.split("•")[1].trim() : "";
            item.time = String.format(Locale.getDefault(), "%02d:%02d • %s", hourOfDay, minute, details);
            updateAlarmInFirestore(item);
            scheduleAlarm(item, alarms.indexOf(item));
        }, item.hour, item.minute, true).show();
    }

    private void showEditTitleDialog(AlarmItem item) {
        EditText input = new EditText(this);
        input.setText(item.title);
        input.setPadding(50, 40, 50, 40);
        new AlertDialog.Builder(this).setTitle("Editar nome").setView(input).setPositiveButton("Guardar", (dialog, which) -> {
            String newTitle = input.getText().toString().trim();
            if (!TextUtils.isEmpty(newTitle)) {
                item.title = newTitle;
                updateAlarmInFirestore(item);
            }
        }).setNegativeButton("Cancelar", null).show();
    }

    private void scheduleAlarm(AlarmItem item, int alarmId) {
        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(this, AlarmReceiver.class);
        intent.putExtra("alarm_title", item.title);
        intent.putExtra("alarm_id", alarmId);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, alarmId, intent, PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT);

        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, item.hour);
        calendar.set(Calendar.MINUTE, item.minute);
        calendar.set(Calendar.SECOND, 0);
        if (calendar.getTimeInMillis() < System.currentTimeMillis()) {
            calendar.add(Calendar.DAY_OF_MONTH, 1);
        }

        try {
            alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
        } catch (SecurityException e) {
            Toast.makeText(this, "Erro: Permissão de alarme necessária", Toast.LENGTH_SHORT).show();
        }
    }

    private void loadAlarmsFromFirestore() {
        if (currentUserId == null) return;
        db.collection("users").document(currentUserId).collection("alarms")
                .get()
                .addOnCompleteListener(task -> {
                    if (task.isSuccessful()) {
                        alarms.clear();
                        for (QueryDocumentSnapshot document : task.getResult()) {
                            AlarmItem item = document.toObject(AlarmItem.class);
                            item.documentId = document.getId();
                            alarms.add(item);
                        }
                        renderAlarms();
                        if (calendarView != null) {
                            setupCalendar(calendarView);
                        }
                    } else {
                        Log.e("Firestore", "Error loading alarms: ", task.getException());
                    }
                });
    }

    private void saveAlarmInFirestore(AlarmItem item) {
        if (currentUserId == null) return;
        db.collection("users").document(currentUserId).collection("alarms")
                .add(item)
                .addOnSuccessListener(documentReference -> {
                    item.documentId = documentReference.getId();
                    if (!alarms.contains(item)) {
                        alarms.add(item);
                    }
                    int alarmId = alarms.indexOf(item);
                    scheduleAlarm(item, alarmId);
                    renderAlarms();
                    Toast.makeText(this, "Alarme criado e agendado!", Toast.LENGTH_SHORT).show();
                })
                .addOnFailureListener(e -> Toast.makeText(this, "Erro ao guardar alarme", Toast.LENGTH_SHORT).show());
    }

    private void updateAlarmInFirestore(AlarmItem item) {
        if (currentUserId == null || item.documentId == null) return;
        db.collection("users").document(currentUserId).collection("alarms").document(item.documentId)
                .set(item)
                .addOnSuccessListener(aVoid -> {
                    renderAlarms();
                    Toast.makeText(this, "Alarme atualizado!", Toast.LENGTH_SHORT).show();
                })
                .addOnFailureListener(e -> Toast.makeText(this, "Erro ao atualizar alarme", Toast.LENGTH_SHORT).show());
    }

    private void deleteAlarmFromFirestore(AlarmItem item, int index) {
        if (currentUserId == null || item.documentId == null) return;
        db.collection("users").document(currentUserId).collection("alarms").document(item.documentId)
                .delete()
                .addOnSuccessListener(aVoid -> {
                    alarms.remove(index);
                    renderAlarms();
                    Toast.makeText(this, "Alarme removido", Toast.LENGTH_SHORT).show();
                })
                .addOnFailureListener(e -> Toast.makeText(this, "Erro ao remover alarme", Toast.LENGTH_SHORT).show());
    }

     private void showIntroDialogIfNeeded() {
        boolean hasSeenIntro = prefs.getBoolean("has_seen_intro", false);
        if (!hasSeenIntro) {
            View dialogView = inflater.inflate(R.layout.dialog_intro, null);
            AlertDialog dialog = new AlertDialog.Builder(this)
                    .setView(dialogView)
                    .setCancelable(false)
                    .create();

            Button skipButton = dialogView.findViewById(R.id.btnSkipIntro);
            skipButton.setOnClickListener(v -> {
                prefs.edit().putBoolean("has_seen_intro", true).apply();
                dialog.dismiss();
            });

            dialog.show();
        }
    }


    public static class AlarmItem {
        public String documentId;
        public String title;
        public String time;
        public String days;
        public boolean enabled;
        public int hour;
        public int minute;
        public boolean takenToday;
        public long lastTakenTimestamp;
        public String ringtoneUri;
        public String ringtoneName;

        public AlarmItem() { }

        public AlarmItem(String title, String time, String days, boolean enabled) {
            this.title = title;
            this.time = time;
            this.days = days;
            this.enabled = enabled;
            this.hour = 8;
            this.minute = 0;
            this.takenToday = false;
            this.lastTakenTimestamp = 0;
            this.ringtoneUri = null;
            this.ringtoneName = "Toque padrão";
        }
    }
}
