package com.example.pap_teste;

import android.os.Bundle;
import android.text.TextUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

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

import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

import java.util.HashMap;
import java.util.Map;

public class DefinicoesAdminActivity extends AppCompatActivity {

    private EditText inputRadius, inputLatitude, inputLongitude;
    private DatabaseReference databaseReference;
    private String documentId;

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

        String email = getIntent().getStringExtra(MainActivity.EXTRA_EMAIL);
        if (email != null) {
            documentId = email.replace(".", "_").replace("@", "_at_");
        }

        databaseReference = FirebaseDatabase.getInstance().getReference().child("users");

        inputRadius = findViewById(R.id.inputRadius);
        inputLatitude = findViewById(R.id.inputLatitude);
        inputLongitude = findViewById(R.id.inputLongitude);
        Button btnSave = findViewById(R.id.btnSaveSettings);
        Button btnBack = findViewById(R.id.btnVoltar);

        if (btnBack != null) {
            btnBack.setOnClickListener(v -> finish());
        }

        loadCurrentSettings();

        btnSave.setOnClickListener(v -> saveSettings());
    }

    private void loadCurrentSettings() {
        if (documentId == null)
            return;

        databaseReference.child(documentId).addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                if (snapshot.exists()) {
                    if (snapshot.hasChild("securityDistance")) {
                        Object val = snapshot.child("securityDistance").getValue();
                        inputRadius.setText(val != null ? val.toString() : "");
                    }
                    if (snapshot.hasChild("latitude")) {
                        Object val = snapshot.child("latitude").getValue();
                        inputLatitude.setText(val != null ? val.toString() : "");
                    }
                    if (snapshot.hasChild("longitude")) {
                        Object val = snapshot.child("longitude").getValue();
                        inputLongitude.setText(val != null ? val.toString() : "");
                    }
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {
                Toast.makeText(DefinicoesAdminActivity.this, "Erro ao carregar definições.", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void saveSettings() {
        if (documentId == null)
            return;

        String radiusStr = inputRadius.getText().toString().trim();
        String latStr = inputLatitude.getText().toString().trim();
        String lonStr = inputLongitude.getText().toString().trim();

        if (TextUtils.isEmpty(radiusStr) || TextUtils.isEmpty(latStr) || TextUtils.isEmpty(lonStr)) {
            Toast.makeText(this, "Preencha todos os campos.", Toast.LENGTH_SHORT).show();
            return;
        }

        try {
            int radius = Integer.parseInt(radiusStr);
            double lat = Double.parseDouble(latStr);
            double lon = Double.parseDouble(lonStr);

            Map<String, Object> updates = new HashMap<>();
            updates.put("securityDistance", radius);
            updates.put("latitude", lat);
            updates.put("longitude", lon);

            databaseReference.child(documentId).updateChildren(updates)
                    .addOnSuccessListener(aVoid -> {
                        Toast.makeText(this, "Definições guardadas com sucesso!", Toast.LENGTH_SHORT).show();
                        finish();
                    })
                    .addOnFailureListener(
                            e -> Toast.makeText(this, "Falha ao guardar definições.", Toast.LENGTH_SHORT).show());

        } catch (NumberFormatException e) {
            Toast.makeText(this, "Valores inválidos.", Toast.LENGTH_SHORT).show();
        }
    }
}
