package com.example.pap_teste;

import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

public class EstablishmentDashboardActivity extends AppCompatActivity {

        @Override
        protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                EdgeToEdge.enable(this);
                setContentView(R.layout.activity_establishment_dashboard);
                ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.establishmentRoot), (v, insets) -> {
                        Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
                        v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
                        return insets;
                });

                TextView txtTitle = findViewById(R.id.txtEstabTitle);
                TextView txtSubtitle = findViewById(R.id.txtEstabSubtitle);
                TextView txtRole = findViewById(R.id.txtEstabRole);

                String actionMode = getIntent().getStringExtra(MainActivity.EXTRA_ACTION_MODE);
                String displayName = getIntent().getStringExtra(MainActivity.EXTRA_DISPLAY_NAME);
                String role = getIntent().getStringExtra(MainActivity.EXTRA_ROLE);

                boolean isNewAccount = "CRIAR".equalsIgnoreCase(actionMode);
                txtTitle.setText(displayName != null ? displayName : "Estabelecimento");
                txtRole.setText(String.format("Função: %s", role != null ? role : "ADMIN"));
                txtSubtitle.setText(isNewAccount
                                ? "Perfil criado. Configure horários, mesas e abra reservas."
                                : "Dashboard operacional. Acompanhe as reservas em tempo real.");

                Button btnOpenWalkIns = findViewById(R.id.btnAbrirEspera);
                Button btnStaff = findViewById(R.id.btnGestaoStaff);
                Button btnGerirMesas = findViewById(R.id.btnGerirMesas);
                Button btnDetails = findViewById(R.id.btnDetalhesReservas);
                Button btnSettings = findViewById(R.id.btnDefinicoes);
                Button btnBack = findViewById(R.id.btnVoltar);

                String email = getIntent().getStringExtra(MainActivity.EXTRA_EMAIL);
                if (email == null) {
                    if (com.google.firebase.auth.FirebaseAuth.getInstance().getCurrentUser() != null) {
                        email = com.google.firebase.auth.FirebaseAuth.getInstance().getCurrentUser().getEmail();
                    } else {
                        return; // Can't proceed without email
                    }
                }
                final String finalEmail = email;

                btnOpenWalkIns.setOnClickListener(v -> {
                        Intent intent = new Intent(this, ListaEsperaActivity.class);
                        intent.putExtra(MainActivity.EXTRA_EMAIL, finalEmail);
                        startActivity(intent);
                });

                btnStaff.setOnClickListener(v -> {
                        Intent intent = new Intent(this, GestaoStaffActivity.class);
                        intent.putExtra(MainActivity.EXTRA_EMAIL, finalEmail);
                        startActivity(intent);
                });

                btnGerirMesas.setOnClickListener(v -> {
                        Intent intent = new Intent(this, GerirMesasActivity.class);
                        intent.putExtra(MainActivity.EXTRA_EMAIL, finalEmail);
                        startActivity(intent);
                });

                btnDetails.setOnClickListener(v -> {
                        Intent intent = new Intent(this, DetalhesReservasActivity.class);
                        intent.putExtra(MainActivity.EXTRA_EMAIL, finalEmail);
                        startActivity(intent);
                });

                btnSettings.setOnClickListener(v -> {
                        Intent intent = new Intent(this, DefinicoesAdminActivity.class);
                        intent.putExtra(MainActivity.EXTRA_EMAIL, finalEmail);
                        startActivity(intent);
                });

                findViewById(R.id.cardReservasHoje).setOnClickListener(v -> {
                        Intent intent = new Intent(this, DetalhesReservasActivity.class);
                        intent.putExtra(MainActivity.EXTRA_EMAIL, finalEmail);
                        startActivity(intent);
                });

                if (btnBack != null) {

                        btnBack.setOnClickListener(v -> finish());
                }

                loadProximasReservas();
                loadEstatisticas();
                checkPendingReservationsOnLogin();
        }

        private void loadProximasReservas() {
                android.widget.LinearLayout llProximasReservas = findViewById(R.id.llProximasReservas);
                String email = getIntent().getStringExtra(MainActivity.EXTRA_EMAIL);
                if (email == null) {
                    if (com.google.firebase.auth.FirebaseAuth.getInstance().getCurrentUser() != null) {
                        email = com.google.firebase.auth.FirebaseAuth.getInstance().getCurrentUser().getEmail();
                    } else {
                        return;
                    }
                }
                
                final String targetEmail = email != null ? email.trim() : "";

                java.util.Calendar cal = java.util.Calendar.getInstance();
                String todayDate = cal.get(java.util.Calendar.DAY_OF_MONTH) + "/" + 
                        (cal.get(java.util.Calendar.MONTH) + 1) + "/" + 
                        cal.get(java.util.Calendar.YEAR);

                com.google.firebase.database.FirebaseDatabase.getInstance().getReference("reservas")
                        .addValueEventListener(new com.google.firebase.database.ValueEventListener() {
                            @Override
                            public void onDataChange(@androidx.annotation.NonNull com.google.firebase.database.DataSnapshot snapshot) {
                                llProximasReservas.removeAllViews();
                                boolean found = false;

                                for (com.google.firebase.database.DataSnapshot ds : snapshot.getChildren()) {
                                    com.example.pap_teste.models.Reserva r = ds.getValue(com.example.pap_teste.models.Reserva.class);
                                    if (r != null && r.getEstado() != null && (r.getEstado().startsWith("Confirmada") || r.getEstado().equals("Concluída")) && todayDate.equals(r.getData())) {
                                        String rEmail = r.getRestauranteEmail();
                                        if (rEmail != null && rEmail.trim().equalsIgnoreCase(targetEmail)) {
                                            found = true;
                                            addReservaView(llProximasReservas, r);
                                        }
                                    }
                                }

                                if (!found) {
                                    TextView empty = new TextView(EstablishmentDashboardActivity.this);
                                    empty.setText("Não há reservas confirmadas para hoje.");
                                    empty.setTextColor(android.graphics.Color.parseColor("#5F5F5F"));
                                    empty.setTextSize(14f);
                                    llProximasReservas.addView(empty);
                                }
                            }

                            @Override
                            public void onCancelled(@androidx.annotation.NonNull com.google.firebase.database.DatabaseError error) {
                            }
                        });
        }

        private void addReservaView(android.widget.LinearLayout container, com.example.pap_teste.models.Reserva r) {
                TextView title = new TextView(this);
                title.setText(String.format("%s - %s", r.getHora(), r.getData()));
                title.setTextColor(android.graphics.Color.BLACK);
                title.setTextSize(16f);
                title.setTypeface(null, android.graphics.Typeface.BOLD);

                TextView subtitle = new TextView(this);
                subtitle.setText(String.format("Cliente: %s • %d pessoas", r.getClienteEmail(), r.getPessoas()));
                subtitle.setTextColor(android.graphics.Color.parseColor("#5F5F5F"));
                subtitle.setTextSize(14f);
                
                android.widget.LinearLayout.LayoutParams params = new android.widget.LinearLayout.LayoutParams(
                        android.widget.LinearLayout.LayoutParams.MATCH_PARENT, android.widget.LinearLayout.LayoutParams.WRAP_CONTENT);
                subtitle.setLayoutParams(params);

                android.view.View divider = new android.view.View(this);
                android.widget.LinearLayout.LayoutParams divParams = new android.widget.LinearLayout.LayoutParams(
                        android.widget.LinearLayout.LayoutParams.MATCH_PARENT, 2);
                divParams.setMargins(0, 24, 0, 24);
                divider.setLayoutParams(divParams);
                divider.setBackgroundColor(android.graphics.Color.parseColor("#EEEEEE"));

                container.addView(title);
                container.addView(subtitle);
                container.addView(divider);
        }

        private void loadEstatisticas() {
                TextView txtReservasHoje = findViewById(R.id.txtReservasHojeDash);
                TextView txtMesasLivres = findViewById(R.id.txtMesasLivresDash);
                TextView txtListaEspera = findViewById(R.id.txtListaEsperaDash);

                String email = getIntent().getStringExtra(MainActivity.EXTRA_EMAIL);
                if (email == null) {
                    if (com.google.firebase.auth.FirebaseAuth.getInstance().getCurrentUser() != null) {
                        email = com.google.firebase.auth.FirebaseAuth.getInstance().getCurrentUser().getEmail();
                    } else {
                        return;
                    }
                }
                final String finalEmail = email != null ? email.trim() : "";

                java.util.Calendar cal = java.util.Calendar.getInstance();
                String todayDate = cal.get(java.util.Calendar.DAY_OF_MONTH) + "/" + 
                        (cal.get(java.util.Calendar.MONTH) + 1) + "/" + 
                        cal.get(java.util.Calendar.YEAR);

                com.google.firebase.database.DatabaseReference refReservas = com.google.firebase.database.FirebaseDatabase.getInstance().getReference("reservas");
                refReservas.addValueEventListener(new com.google.firebase.database.ValueEventListener() {
                            @Override
                            public void onDataChange(@androidx.annotation.NonNull com.google.firebase.database.DataSnapshot snapshot) {
                                int reservasHoje = 0;
                                int listaEspera = 0;
                                for (com.google.firebase.database.DataSnapshot ds : snapshot.getChildren()) {
                                    com.example.pap_teste.models.Reserva r = ds.getValue(com.example.pap_teste.models.Reserva.class);
                                    if (r != null && r.getRestauranteEmail() != null && r.getRestauranteEmail().trim().equalsIgnoreCase(finalEmail)) {
                                        if (r.getEstado() != null) {
                                            if ((r.getEstado().startsWith("Confirmada") || r.getEstado().equals("Concluída") || r.getEstado().equals("Arquivada")) && todayDate.equals(r.getData())) {
                                                reservasHoje++;
                                            } else if ("Pendente".equals(r.getEstado())) {
                                                listaEspera++;
                                            }
                                        }
                                    }
                                }
                                if (txtReservasHoje != null) txtReservasHoje.setText(String.format(java.util.Locale.US, "%02d", reservasHoje));
                                if (txtListaEspera != null) txtListaEspera.setText(String.format(java.util.Locale.US, "%02d", listaEspera));
                            }

                            @Override
                            public void onCancelled(@androidx.annotation.NonNull com.google.firebase.database.DatabaseError error) {
                            }
                        });

                com.google.firebase.database.FirebaseDatabase.getInstance().getReference("Mesas")
                        .addValueEventListener(new com.google.firebase.database.ValueEventListener() {
                            @Override
                            public void onDataChange(@androidx.annotation.NonNull com.google.firebase.database.DataSnapshot snapshot) {
                                int totalMesas = 0;
                                int mesasOcupadas = 0;
                                int mesasLivres = 0;
                                for (com.google.firebase.database.DataSnapshot ds : snapshot.getChildren()) {
                                    com.example.pap_teste.models.Mesa mesa = ds.getValue(com.example.pap_teste.models.Mesa.class);
                                    if (mesa != null && (mesa.getRestauranteEmail() == null || mesa.getRestauranteEmail().trim().equalsIgnoreCase(finalEmail))) {
                                        totalMesas++;
                                        if ("Ocupada".equalsIgnoreCase(mesa.getEstado()) || "Reservada".equalsIgnoreCase(mesa.getEstado())) {
                                            mesasOcupadas++;
                                        } else if ("Livre".equalsIgnoreCase(mesa.getEstado())) {
                                            mesasLivres++;
                                        }
                                    }
                                }
                                if (txtMesasLivres != null) txtMesasLivres.setText(mesasOcupadas + " / " + totalMesas);
                                TextView txtMesasLivresSub = findViewById(R.id.txtMesasLivresSub);
                                if (txtMesasLivresSub != null) txtMesasLivresSub.setText(mesasLivres + " livres");
                            }
                            @Override
                            public void onCancelled(@androidx.annotation.NonNull com.google.firebase.database.DatabaseError error) {
                            }
                        });
        }

        private void checkPendingReservationsOnLogin() {
                String email = getIntent().getStringExtra(MainActivity.EXTRA_EMAIL);
                if (email == null) {
                    if (com.google.firebase.auth.FirebaseAuth.getInstance().getCurrentUser() != null) {
                        email = com.google.firebase.auth.FirebaseAuth.getInstance().getCurrentUser().getEmail();
                    } else {
                        return;
                    }
                }
                final String finalEmail = email != null ? email.trim() : "";

                com.google.firebase.database.FirebaseDatabase.getInstance().getReference("reservas")
                        .addListenerForSingleValueEvent(new com.google.firebase.database.ValueEventListener() {
                            @Override
                            public void onDataChange(@androidx.annotation.NonNull com.google.firebase.database.DataSnapshot snapshot) {
                                java.util.List<com.example.pap_teste.models.Reserva> pendingReservations = new java.util.ArrayList<>();
                                for (com.google.firebase.database.DataSnapshot ds : snapshot.getChildren()) {
                                    com.example.pap_teste.models.Reserva r = ds.getValue(com.example.pap_teste.models.Reserva.class);
                                    if (r != null && r.getRestauranteEmail() != null && r.getRestauranteEmail().trim().equalsIgnoreCase(finalEmail)) {
                                        if ("Pendente".equals(r.getEstado())) {
                                            pendingReservations.add(r);
                                        }
                                    }
                                }

                                if (!pendingReservations.isEmpty()) {
                                    showPendingReservationsDialog(pendingReservations);
                                }
                            }

                            @Override
                            public void onCancelled(@androidx.annotation.NonNull com.google.firebase.database.DatabaseError error) {
                            }
                        });
        }

        private void showPendingReservationsDialog(java.util.List<com.example.pap_teste.models.Reserva> pendingReservations) {
                if (isFinishing() || isDestroyed()) return;
                android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(this);
                builder.setTitle("Reservas Pendentes (" + pendingReservations.size() + ")");
                
                StringBuilder message = new StringBuilder("Tem reservas a aguardar confirmação:\n\n");
                for (com.example.pap_teste.models.Reserva r : pendingReservations) {
                    message.append("• ").append(r.getData()).append(" às ").append(r.getHora())
                           .append(" - ").append(r.getPessoas()).append(" pessoas")
                           .append("\n  Cliente: ").append(r.getClienteEmail()).append("\n\n");
                }
                
                builder.setMessage(message.toString());
                builder.setPositiveButton("Ver Reservas", (dialog, which) -> {
                    Intent intent = new Intent(EstablishmentDashboardActivity.this, DetalhesReservasActivity.class);
                    intent.putExtra(MainActivity.EXTRA_EMAIL, getIntent().getStringExtra(MainActivity.EXTRA_EMAIL));
                    startActivity(intent);
                });
                builder.setNegativeButton("Fechar", (dialog, which) -> dialog.dismiss());
                
                android.app.AlertDialog dialog = builder.create();
                dialog.show();
                
                android.widget.TextView textView = dialog.findViewById(android.R.id.message);
                if (textView != null) {
                    textView.setTextSize(18);
                    textView.setGravity(android.view.Gravity.CENTER);
                }
        }
}
