package com.example.pap_teste;

import android.os.Bundle;

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 android.widget.Button;

public class ExplorarRestaurantesActivity extends AppCompatActivity {

    private enum State {
        LIST, DETAILS
    }

    private State currentState = State.LIST;
    private com.example.pap_teste.models.Restaurant selectedRestaurant = null;

    private android.view.View scrollReservaDetails;
    private androidx.recyclerview.widget.RecyclerView rvRestaurants;
    private android.widget.TextView txtTitle;

    private String selectedDate = null;
    private String selectedTime = null;

    private final androidx.activity.result.ActivityResultLauncher<android.content.Intent> photoPickerLauncher = registerForActivityResult(
            new androidx.activity.result.contract.ActivityResultContracts.StartActivityForResult(),
            result -> {
                if (result.getResultCode() == RESULT_OK && result.getData() != null) {
                    android.net.Uri imageUri = result.getData().getData();
                    if (imageUri != null) {
                        uploadRestaurantPhoto(imageUri);
                    }
                }
            });


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

        rvRestaurants = findViewById(R.id.rvRestaurants);
        scrollReservaDetails = findViewById(R.id.scrollReservaDetails);
        txtTitle = findViewById(R.id.txtTituloExplorar);

        Button back = findViewById(R.id.btnVoltar);
        if (back != null) {
            back.setOnClickListener(v -> handleBackNavigation());
        }

        setupRestaurantList();
        updateViewState();
    }

    private void handleBackNavigation() {
        if (currentState == State.DETAILS) {
            currentState = State.LIST;
            updateViewState();
        } else {
            finish();
        }
    }

    private void updateViewState() {
        rvRestaurants.setVisibility(currentState == State.LIST ? android.view.View.VISIBLE : android.view.View.GONE);
        scrollReservaDetails
                .setVisibility(currentState == State.DETAILS ? android.view.View.VISIBLE : android.view.View.GONE);

        if (currentState == State.LIST) {
            String filter = getIntent().getStringExtra("category_filter");
            txtTitle.setText(filter != null ? "Explorar: " + filter : "Explorar restaurantes");
        } else {
            txtTitle.setText("Reserva: " + (selectedRestaurant != null ? selectedRestaurant.getName() : ""));
            setupReservationOptions();
        }
    }

    private void setupRestaurantList() {
        String filter = getIntent().getStringExtra("category_filter");
        java.util.List<com.example.pap_teste.models.Restaurant> restaurantsList = new java.util.ArrayList<>();
        com.google.firebase.database.DatabaseReference usersRef = com.google.firebase.database.FirebaseDatabase.getInstance().getReference("users");
        
        com.google.firebase.database.Query query = usersRef;
        if (filter != null) {
            query = usersRef.orderByChild("category").equalTo(filter);
        }

        query.addListenerForSingleValueEvent(new com.google.firebase.database.ValueEventListener() {
            @Override
            public void onDataChange(@androidx.annotation.NonNull com.google.firebase.database.DataSnapshot snapshot) {
                restaurantsList.clear();
                for (com.google.firebase.database.DataSnapshot ds : snapshot.getChildren()) {
                    String role = ds.child("role").getValue(String.class);
                    String accountType = ds.child("accountType").getValue(String.class);
                    
                    if ("ADMIN".equalsIgnoreCase(role) || "ESTABELECIMENTO".equalsIgnoreCase(accountType)) {
                        String name = ds.child("establishmentName").getValue(String.class);
                        if (name == null) name = ds.child("displayName").getValue(String.class);
                        String email = ds.child("email").getValue(String.class);
                        String cat = ds.child("category").getValue(String.class);
                        String logoUrl = ds.child("logoUrl").getValue(String.class);
                        
                        if (name != null && email != null) {
                            restaurantsList.add(new com.example.pap_teste.models.Restaurant(name, cat, email, false, logoUrl));
                        }
                    }
                }
                
                RestaurantAdapter adapter = new RestaurantAdapter(restaurantsList, restaurant -> {
                    selectedRestaurant = restaurant;
                    currentState = State.DETAILS;
                    updateViewState();
                });
                rvRestaurants.setAdapter(adapter);
            }

            @Override
            public void onCancelled(@androidx.annotation.NonNull com.google.firebase.database.DatabaseError error) {
                android.widget.Toast.makeText(ExplorarRestaurantesActivity.this, "Erro ao carregar restaurantes.", android.widget.Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void setupReservationOptions() {
        android.widget.Button btnDate = findViewById(R.id.btnSelectDate);
        android.widget.Button btnTime = findViewById(R.id.btnSelectTime);
        android.widget.Button btnVerAvaliacoes = findViewById(R.id.btnVerAvaliacoes);
        android.widget.Button btnUploadFoto = findViewById(R.id.btnUploadFoto);

        btnDate.setOnClickListener(v -> {
            java.util.Calendar cal = java.util.Calendar.getInstance();
            new android.app.DatePickerDialog(this, (view, year, month, dayOfMonth) -> {
                selectedDate = dayOfMonth + "/" + (month + 1) + "/" + year;
                btnDate.setText(selectedDate);
            }, cal.get(java.util.Calendar.YEAR), cal.get(java.util.Calendar.MONTH), cal.get(java.util.Calendar.DAY_OF_MONTH)).show();
        });

        btnTime.setOnClickListener(v -> {
            java.util.Calendar cal = java.util.Calendar.getInstance();
            new android.app.TimePickerDialog(this, (view, hourOfDay, minute) -> {
                selectedTime = String.format(java.util.Locale.getDefault(), "%02d:%02d", hourOfDay, minute);
                btnTime.setText(selectedTime);
            }, cal.get(java.util.Calendar.HOUR_OF_DAY), cal.get(java.util.Calendar.MINUTE), true).show();
        });

        findViewById(R.id.btnConfirmarReserva).setOnClickListener(v -> saveReservation());

        btnVerAvaliacoes.setOnClickListener(v -> showReviewsDialog());

        btnUploadFoto.setOnClickListener(v -> {
            android.content.Intent intent = new android.content.Intent(android.content.Intent.ACTION_PICK);
            intent.setType("image/*");
            photoPickerLauncher.launch(intent);
        });
    }

    private void uploadRestaurantPhoto(android.net.Uri imageUri) {
        if (selectedRestaurant == null || selectedRestaurant.getEmail() == null) return;
        String encodedEmail = selectedRestaurant.getEmail().replace(".", "_").replace("@", "_at_");
        com.google.firebase.storage.StorageReference storageRef = com.google.firebase.storage.FirebaseStorage.getInstance().getReference()
                .child("restaurant_photos/" + encodedEmail + "/" + java.util.UUID.randomUUID().toString());

        storageRef.putFile(imageUri).addOnSuccessListener(taskSnapshot -> {
            storageRef.getDownloadUrl().addOnSuccessListener(uri -> {
                String photoUrl = uri.toString();
                com.google.firebase.database.FirebaseDatabase.getInstance().getReference("photos").child(encodedEmail)
                        .push().child("url").setValue(photoUrl).addOnCompleteListener(task -> {
                            if (task.isSuccessful()) {
                                android.widget.Toast.makeText(this, "Foto adicionada com sucesso!", android.widget.Toast.LENGTH_SHORT).show();
                            }
                        });
            });
        }).addOnFailureListener(e -> {
            android.widget.Toast.makeText(this, "Falha no upload: " + e.getMessage(), android.widget.Toast.LENGTH_LONG).show();
        });
    }

    private void showReviewsDialog() {
        if (selectedRestaurant == null || selectedRestaurant.getEmail() == null) return;
        String encodedEmail = selectedRestaurant.getEmail().replace(".", "_").replace("@", "_at_");

        com.google.firebase.database.DatabaseReference reviewsRef = com.google.firebase.database.FirebaseDatabase.getInstance()
                .getReference("reviews").child(encodedEmail);

        reviewsRef.addListenerForSingleValueEvent(new com.google.firebase.database.ValueEventListener() {
            @Override
            public void onDataChange(@androidx.annotation.NonNull com.google.firebase.database.DataSnapshot snapshot) {
                java.util.List<String> reviewsList = new java.util.ArrayList<>();
                for (com.google.firebase.database.DataSnapshot dst : snapshot.getChildren()) {
                    String author = dst.child("author").getValue(String.class);
                    String text = dst.child("text").getValue(String.class);
                    if (author != null && text != null) {
                        reviewsList.add(author + "\n" + text);
                    }
                }

                String[] reviewsArray = reviewsList.toArray(new String[0]);
                androidx.appcompat.app.AlertDialog.Builder builder = new androidx.appcompat.app.AlertDialog.Builder(ExplorarRestaurantesActivity.this)
                        .setTitle("Avaliações")
                        .setItems(reviewsArray, null)
                        .setPositiveButton("Fechar", null)
                        .setNeutralButton("Adicionar", (dialog, which) -> addReviewDialog());
                
                if (reviewsList.isEmpty()) {
                    builder.setMessage("Ainda sem avaliações.");
                }
                builder.show();
            }

            @Override
            public void onCancelled(@androidx.annotation.NonNull com.google.firebase.database.DatabaseError error) {
                android.widget.Toast.makeText(ExplorarRestaurantesActivity.this, "Erro ao carregar avaliações.", android.widget.Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void addReviewDialog() {
        if (selectedRestaurant == null || selectedRestaurant.getEmail() == null) return;

        android.widget.EditText input = new android.widget.EditText(this);
        input.setHint("Escreva a sua avaliação aqui...");
        new androidx.appcompat.app.AlertDialog.Builder(this)
                .setTitle("Adicionar Avaliação")
                .setView(input)
                .setPositiveButton("Enviar", (dialog, which) -> {
                    String revText = input.getText().toString().trim();
                    if (!revText.isEmpty()) {
                        com.google.firebase.auth.FirebaseUser currentUser = com.google.firebase.auth.FirebaseAuth.getInstance().getCurrentUser();
                        if (currentUser != null && currentUser.getEmail() != null) {
                            String userDoc = currentUser.getEmail().replace(".", "_").replace("@", "_at_");
                            com.google.firebase.database.FirebaseDatabase.getInstance().getReference("users").child(userDoc).get().addOnSuccessListener(snapshot -> {
                                String authorName = snapshot.exists() && snapshot.child("displayName").getValue(String.class) != null
                                        ? snapshot.child("displayName").getValue(String.class)
                                        : "Visitante";
                                submitReviewToFirebase(authorName, revText);
                            }).addOnFailureListener(e -> submitReviewToFirebase("Visitante", revText));
                        } else {
                            submitReviewToFirebase("Visitante", revText);
                        }
                    }
                })
                .setNegativeButton("Cancelar", null)
                .show();
    }

    private void submitReviewToFirebase(String authorName, String revText) {
        String encodedEmail = selectedRestaurant.getEmail().replace(".", "_").replace("@", "_at_");
        java.util.Map<String, Object> review = new java.util.HashMap<>();
        review.put("author", authorName);
        review.put("text", revText);

        com.google.firebase.database.FirebaseDatabase.getInstance().getReference("reviews")
                .child(encodedEmail).push().setValue(review).addOnCompleteListener(task -> {
                    if (task.isSuccessful()) {
                        android.widget.Toast.makeText(this, "Avaliação enviada!", android.widget.Toast.LENGTH_SHORT).show();
                    }
                });
    }

    private void saveReservation() {
        android.widget.EditText etPartySize = findViewById(R.id.etPartySize);
        int partySize = 0;
        try {
            partySize = Integer.parseInt(etPartySize.getText().toString());
        } catch (Exception e) {}

        if (selectedDate == null || selectedTime == null || partySize == 0) {
            android.widget.Toast.makeText(this, "Por favor, selecione data, hora e número de pessoas.",
                    android.widget.Toast.LENGTH_SHORT).show();
            return;
        }

        String userEmail = com.google.firebase.auth.FirebaseAuth.getInstance().getCurrentUser() != null
                ? com.google.firebase.auth.FirebaseAuth.getInstance().getCurrentUser().getEmail()
                : "cliente@teste.com";

        com.google.firebase.database.DatabaseReference ref = com.google.firebase.database.FirebaseDatabase.getInstance()
                .getReference("reservas");
        String id = ref.push().getKey();

        com.example.pap_teste.models.Reserva reserva = new com.example.pap_teste.models.Reserva(
                id,
                userEmail,
                selectedRestaurant.getName(),
                selectedRestaurant.getEmail(),
                selectedDate,
                selectedTime,
                partySize,
                "Pendente");

        if (id != null) {
            ref.child(id).setValue(reserva).addOnCompleteListener(task -> {
                if (task.isSuccessful()) {
                    android.widget.Toast
                            .makeText(this, "Reserva solicitada com sucesso!", android.widget.Toast.LENGTH_SHORT)
                            .show();
                    finish();
                } else {
                    android.widget.Toast.makeText(this, "Erro ao salvar reserva.", android.widget.Toast.LENGTH_SHORT)
                            .show();
                }
            });
        }
    }
}
