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;

import androidx.recyclerview.widget.RecyclerView;
import com.example.pap_teste.models.FoodCategory;
import java.util.ArrayList;
import java.util.List;

public class ClientDashboardActivity extends AppCompatActivity {

        private String email, displayName, role;
        private TextView txtGreeting;
        private androidx.activity.result.ActivityResultLauncher<Intent> profileLauncher;

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

                txtGreeting = findViewById(R.id.txtClientGreeting);

                email = getIntent().getStringExtra(MainActivity.EXTRA_EMAIL);
                displayName = getIntent().getStringExtra(MainActivity.EXTRA_DISPLAY_NAME);
                role = getIntent().getStringExtra(MainActivity.EXTRA_ROLE);

                profileLauncher = registerForActivityResult(
                                new androidx.activity.result.contract.ActivityResultContracts.StartActivityForResult(),
                                result -> {
                                        if (result.getResultCode() == RESULT_OK && result.getData() != null) {
                                                String updatedName = result.getData()
                                                                .getStringExtra(MainActivity.EXTRA_DISPLAY_NAME);
                                                if (updatedName != null) {
                                                        displayName = updatedName;
                                                        updateGreeting();
                                                }
                                        }
                                });

                updateGreeting();
                fetchProfilePicture();
                setupCategories();
                setupActions();
                loadNextReservation();
        }

        private void updateGreeting() {
                txtGreeting.setText(String.format("Olá, %s", displayName != null ? displayName : "convidado"));
        }

        private void fetchProfilePicture() {
                if (email == null) return;
                String documentId = email.replace(".", "_").replace("@", "_at_");
                com.google.firebase.database.FirebaseDatabase.getInstance().getReference()
                        .child("users").child(documentId).child("photoUrl")
                        .get().addOnSuccessListener(snapshot -> {
                                if (!isDestroyed() && snapshot.exists()) {
                                        String photoUrl = snapshot.getValue(String.class);
                                        if (photoUrl != null && !photoUrl.isEmpty()) {
                                                android.widget.ImageView imgProfile = findViewById(R.id.imgProfile);
                                                com.bumptech.glide.Glide.with(this).load(photoUrl).circleCrop().into(imgProfile);
                                        }
                                }
                        });
        }

        private void setupCategories() {
                RecyclerView rv = findViewById(R.id.rvCategories);
                List<FoodCategory> cats = new ArrayList<>();
                cats.add(new FoodCategory("Carnes", R.drawable.cat_carnes));
                cats.add(new FoodCategory("Massas", R.drawable.cat_massas));
                cats.add(new FoodCategory("Sushi", R.drawable.cat_sushi));
                // Using circle_bg as placeholder for missing images
                cats.add(new FoodCategory("Pizzas", R.drawable.circle_bg));
                cats.add(new FoodCategory("Sobremesas", R.drawable.circle_bg));

                FoodCategoryAdapter adapter = new FoodCategoryAdapter(cats, category -> {
                        Intent intent = new Intent(this, ExplorarRestaurantesActivity.class);
                        intent.putExtra("category_filter", category.getName());
                        startActivity(intent);
                });
                rv.setAdapter(adapter);
        }

        private void setupActions() {
                findViewById(R.id.cardProfile).setOnClickListener(v -> {
                        Intent intent = new Intent(this, ProfileDashboardActivity.class);
                        intent.putExtra(MainActivity.EXTRA_EMAIL, email);
                        intent.putExtra(MainActivity.EXTRA_DISPLAY_NAME, displayName);
                        profileLauncher.launch(intent);
                });

                findViewById(R.id.btnVoltar).setOnClickListener(v -> finish());

                findViewById(R.id.btnPartilhar).setOnClickListener(
                                v -> startActivity(new Intent(this, PartilharReservaActivity.class)));

                findViewById(R.id.btnNovaReserva)
                                .setOnClickListener(v -> startActivity(new Intent(this, NovaReservaActivity.class)));

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

        private void loadNextReservation() {
                if (email == null) return;
                com.google.firebase.database.DatabaseReference ref = com.google.firebase.database.FirebaseDatabase.getInstance().getReference("reservas");
                ref.orderByChild("clienteEmail").equalTo(email).addValueEventListener(new com.google.firebase.database.ValueEventListener() {
                        @Override
                        public void onDataChange(com.google.firebase.database.DataSnapshot snapshot) {
                                com.example.pap_teste.models.Reserva proxima = null;
                                long timeProx = Long.MAX_VALUE;
                                long currentTime = System.currentTimeMillis();
                                java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("dd/MM/yyyy HH:mm", java.util.Locale.getDefault());

                                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().startsWith("Confirmada") || r.getEstado().equals("Pendente"))) {
                                                try {
                                                        java.util.Date rDate = sdf.parse(r.getData() + " " + r.getHora());
                                                        if (rDate != null) {
                                                                long rTime = rDate.getTime();
                                                                // Consider reservations from the last 2 hours and in the future
                                                                if (rTime >= currentTime - 2L * 60 * 60 * 1000) {
                                                                        if (rTime < timeProx) {
                                                                                timeProx = rTime;
                                                                                proxima = r;
                                                                        }
                                                                }
                                                        }
                                                } catch (Exception e) {
                                                        e.printStackTrace();
                                                }
                                        }
                                }

                                TextView txtTitle = findViewById(R.id.txtResTitle);
                                TextView txtTime = findViewById(R.id.txtResTime);
                                Button btnCheckIn = findViewById(R.id.btnCheckIn);
                                Button btnPartilhar = findViewById(R.id.btnPartilhar);

                                if (proxima != null) {
                                        txtTitle.setText(proxima.getRestauranteName());
                                        
                                        // Formatting to show "Hoje", "Amanhã" or the date itself
                                        String dateStr = proxima.getData();
                                        try {
                                                java.util.Date rDate = sdf.parse(proxima.getData() + " " + proxima.getHora());
                                                if (rDate != null) {
                                                        java.util.Calendar cal = java.util.Calendar.getInstance();
                                                        cal.setTime(rDate);
                                                        
                                                        java.util.Calendar today = java.util.Calendar.getInstance();
                                                        
                                                        java.util.Calendar tmr = java.util.Calendar.getInstance();
                                                        tmr.add(java.util.Calendar.DAY_OF_YEAR, 1);
                                                        
                                                        if (cal.get(java.util.Calendar.YEAR) == today.get(java.util.Calendar.YEAR) && cal.get(java.util.Calendar.DAY_OF_YEAR) == today.get(java.util.Calendar.DAY_OF_YEAR)) {
                                                                dateStr = "Hoje";
                                                        } else if (cal.get(java.util.Calendar.YEAR) == tmr.get(java.util.Calendar.YEAR) && cal.get(java.util.Calendar.DAY_OF_YEAR) == tmr.get(java.util.Calendar.DAY_OF_YEAR)) {
                                                                dateStr = "Amanhã";
                                                        }
                                                }
                                        } catch (Exception e) {
                                                // ignore
                                        }
                                        
                                        txtTime.setText(String.format("%s às %s • %d pessoas", dateStr, proxima.getHora(), proxima.getPessoas()));
                                        btnCheckIn.setVisibility(android.view.View.VISIBLE);
                                        btnPartilhar.setVisibility(android.view.View.VISIBLE);

                                        String encodedEmail = proxima.getRestauranteEmail().replace(".", "_").replace("@", "_at_");
                                        com.google.firebase.database.FirebaseDatabase.getInstance().getReference("users").child(encodedEmail)
                                                .child("logoUrl").get().addOnSuccessListener(s -> {
                                                        if (!isDestroyed() && s.exists() && s.getValue() != null) {
                                                                android.widget.ImageView imgResIcon = findViewById(R.id.imgResIcon);
                                                                com.bumptech.glide.Glide.with(ClientDashboardActivity.this).load(s.getValue(String.class)).circleCrop().into(imgResIcon);
                                                        }
                                                });

                                        com.example.pap_teste.models.Reserva finalProxima = proxima;
                                        btnCheckIn.setOnClickListener(v -> {
                                                boolean hasLocationPermission = androidx.core.app.ActivityCompat.checkSelfPermission(ClientDashboardActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION) == android.content.pm.PackageManager.PERMISSION_GRANTED;
                                                if (!hasLocationPermission) {
                                                        android.widget.Toast.makeText(ClientDashboardActivity.this, "Dê permissões de localização para aceder ao check-in.", android.widget.Toast.LENGTH_SHORT).show();
                                                } else {
                                                        Intent intent = new Intent(ClientDashboardActivity.this, CheckInAntecipadoActivity.class);
                                                        intent.putExtra("restaurant_email", finalProxima.getRestauranteEmail());
                                                        startActivity(intent);
                                                }
                                        });
                                } else {
                                        txtTitle.setText("Sem reservas ativas");
                                        txtTime.setText("Explore os restaurantes e reserve!");
                                        btnCheckIn.setVisibility(android.view.View.GONE);
                                        btnPartilhar.setVisibility(android.view.View.GONE);
                                        android.widget.ImageView imgResIcon = findViewById(R.id.imgResIcon);
                                        imgResIcon.setImageResource(R.drawable.circle_bg);
                                }
                        }
                        @Override
                        public void onCancelled(com.google.firebase.database.DatabaseError error) {}
                });
        }
}
