package com.example.pap_findu;

import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.CircleOptions;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.firebase.firestore.FirebaseFirestore;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

public class AddZoneActivity extends AppCompatActivity implements OnMapReadyCallback {

    private double zoneLat = 0.0;
    private double zoneLng = 0.0;
    private String zoneAddressStr = "";

    private FirebaseFirestore db;
    private GoogleMap mMap;

    private EditText editName;
    private EditText editSearchAddress;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_zone);

        db = FirebaseFirestore.getInstance();

        ImageButton btnBack = findViewById(R.id.btnBack);
        Button btnSave = findViewById(R.id.btnSave);
        editName = findViewById(R.id.editZoneName);
        editSearchAddress = findViewById(R.id.editSearchAddress);
        ImageButton btnSearch = findViewById(R.id.btnSearch);

        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.mapFragment);
        if (mapFragment != null) {
            mapFragment.getMapAsync(this);
        }

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

        btnSearch.setOnClickListener(v -> searchAddress());

        editSearchAddress.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH ||
                    (event != null && event.getAction() == KeyEvent.ACTION_DOWN && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                searchAddress();
                return true;
            }
            return false;
        });

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

    @Override
    public void onMapReady(@NonNull GoogleMap googleMap) {
        mMap = googleMap;

        // Verifica se abriu do Mapa da main com as coordenadas
        if (getIntent().hasExtra("lat") && getIntent().hasExtra("lng")) {
            zoneLat = getIntent().getDoubleExtra("lat", 0);
            zoneLng = getIntent().getDoubleExtra("lng", 0);
            LatLng startLocation = new LatLng(zoneLat, zoneLng);
            mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(startLocation, 14f));
            updateMapMarker(startLocation);
        } else {
            // Posiciona inicial aprox em PT (Opcional, ou deixa o padrao do maps com o mundo)
            mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(39.3999, -8.2245), 6f));
        }

        mMap.setOnMapClickListener(latLng -> {
            zoneLat = latLng.latitude;
            zoneLng = latLng.longitude;
            zoneAddressStr = "Local selecionado no mapa";
            
            updateMapMarker(latLng);
        });
    }

    private void searchAddress() {
        String location = editSearchAddress.getText().toString();
        if (location.isEmpty()) {
            Toast.makeText(this, "Digite um endereço para pesquisar", Toast.LENGTH_SHORT).show();
            return;
        }

        Geocoder geocoder = new Geocoder(this, Locale.getDefault());
        try {
            List<Address> addresses = geocoder.getFromLocationName(location, 1);
            if (addresses != null && !addresses.isEmpty()) {
                Address address = addresses.get(0);
                LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());
                
                zoneLat = latLng.latitude;
                zoneLng = latLng.longitude;
                
                StringBuilder addressBuilder = new StringBuilder();
                for (int i = 0; i <= address.getMaxAddressLineIndex(); i++) {
                    addressBuilder.append(address.getAddressLine(i)).append(" ");
                }
                zoneAddressStr = addressBuilder.toString().trim();
                
                mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 14f));
                updateMapMarker(latLng);
            } else {
                Toast.makeText(this, "Endereço não encontrado", Toast.LENGTH_SHORT).show();
            }
        } catch (IOException e) {
            Toast.makeText(this, "Erro ao buscar endereço", Toast.LENGTH_SHORT).show();
        }
    }

    private void updateMapMarker(LatLng latLng) {
        if (mMap != null) {
            mMap.clear(); // Limpa marcadores e circulos antigos
            mMap.addMarker(new MarkerOptions().position(latLng).title("Centro da Zona Segura"));
            
            mMap.addCircle(new CircleOptions()
                    .center(latLng)
                    .radius(200.0) // 200m
                    .strokeColor(0xFF006400) // Verde escuro
                    .fillColor(0x3300FF00) // Verde semi-transparente
                    .strokeWidth(5f));
        }
    }

    private void saveZone(Button btnSave) {
        String name = editName.getText().toString();

        if (name.isEmpty() || zoneLat == 0.0 || zoneLng == 0.0) {
            Toast.makeText(this, "Preencha o nome e selecione um local no mapa", Toast.LENGTH_SHORT).show();
            return;
        }

        // Isolamento de dados: obter o childCode do filho associado
        String childCode = getSharedPreferences("FindU_Prefs", MODE_PRIVATE).getString("child_access_code", null);
        if (childCode == null) {
            Toast.makeText(this, "Erro: Nenhum filho associado. Adicione um filho primeiro.", Toast.LENGTH_LONG).show();
            return;
        }

        btnSave.setEnabled(false);
        Toast.makeText(this, "Salvando zona...", Toast.LENGTH_SHORT).show();

        Map<String, Object> safeZone = new HashMap<>();
        safeZone.put("name", name);
        safeZone.put("address", zoneAddressStr.isEmpty() ? "Coordenadas: " + zoneLat + ", " + zoneLng : zoneAddressStr);
        safeZone.put("latitude", zoneLat);
        safeZone.put("longitude", zoneLng);
        safeZone.put("radius", 200.0);
        safeZone.put("childCode", childCode);

        db.collection("SafeZones")
                .add(safeZone)
                .addOnSuccessListener(documentReference -> {
                    Toast.makeText(this, "Zona '" + name + "' adicionada com sucesso!", Toast.LENGTH_LONG).show();
                    finish();
                })
                .addOnFailureListener(e -> {
                    Toast.makeText(this, "Erro ao salvar: " + e.getMessage(), Toast.LENGTH_LONG).show();
                    btnSave.setEnabled(true);
                });
    }
}