package com.example.pap_teste;

import android.content.Intent;
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.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import android.view.View;
import android.net.Uri;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import java.util.UUID;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

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

public class ProfileDashboardActivity extends AppCompatActivity {

    private EditText inputName, inputPhone, inputEmailEdit;
    private String email, documentId, photoUrl;
    private DatabaseReference databaseReference;
    private ImageView imgProfile;
    private androidx.activity.result.ActivityResultLauncher<Intent> imagePickerLauncher;

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

        email = getIntent().getStringExtra(MainActivity.EXTRA_EMAIL);
        String currentName = getIntent().getStringExtra(MainActivity.EXTRA_DISPLAY_NAME);

        if (email != null) {
            documentId = email.replace(".", "_").replace("@", "_at_");
        }

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

        inputName = findViewById(R.id.inputProfileName);
        inputPhone = findViewById(R.id.inputProfilePhone);
        inputEmailEdit = findViewById(R.id.inputProfileEmail);
        imgProfile = findViewById(R.id.imgProfile);

        if (currentName != null) {
            inputName.setText(currentName);
        }
        if (email != null) {
            inputEmailEdit.setText(email);
        }

        fetchAdditionalProfileData();

        imagePickerLauncher = 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) {
                            uploadImageToFirebase(imageUri);
                        }
                    }
                });

        findViewById(R.id.cardProfileBig).setOnClickListener(v -> {
            String[] options = {"Galeria", "URL da Imagem"};
            androidx.appcompat.app.AlertDialog.Builder builder = new androidx.appcompat.app.AlertDialog.Builder(this);
            builder.setTitle("Escolher Foto de Perfil");
            builder.setItems(options, (dialog, which) -> {
                if (which == 0) {
                    Intent intent = new Intent(Intent.ACTION_PICK);
                    intent.setType("image/*");
                    imagePickerLauncher.launch(intent);
                } else {
                    showUrlInputDialog();
                }
            });
            builder.show();
        });

        Button btnSave = findViewById(R.id.btnSaveProfile);
        Button btnBack = findViewById(R.id.btnVoltar);
        Button btnFavs = findViewById(R.id.btnFavoritos);
        Button btnRes = findViewById(R.id.btnMinhasReservas);

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

        btnFavs.setOnClickListener(v -> {
            startActivity(new Intent(this, FavoritosActivity.class));
        });

        btnRes.setOnClickListener(v -> {
            startActivity(new Intent(this, MinhasReservasActivity.class));
        });
    }

    private void showUrlInputDialog() {
        androidx.appcompat.app.AlertDialog.Builder builder = new androidx.appcompat.app.AlertDialog.Builder(this);
        builder.setTitle("Inserir URL da Imagem");

        final EditText input = new EditText(this);
        input.setInputType(android.text.InputType.TYPE_TEXT_VARIATION_URI);
        input.setHint("https://exemplo.com/foto.jpg");
        builder.setView(input);

        builder.setPositiveButton("Confirmar", (dialog, which) -> {
            String url = input.getText().toString().trim();
            if (!TextUtils.isEmpty(url)) {
                this.photoUrl = url;
                Glide.with(this).load(photoUrl).circleCrop().into(imgProfile);
                Toast.makeText(this, "URL definida!", Toast.LENGTH_SHORT).show();
            }
        });
        builder.setNegativeButton("Cancelar", (dialog, which) -> dialog.cancel());

        builder.show();
    }

    private void fetchAdditionalProfileData() {
        if (documentId == null)
            return;
        databaseReference.child(documentId).get().addOnSuccessListener(snapshot -> {
            if (snapshot.exists()) {
                String phone = snapshot.child("ownerPhone").getValue(String.class);
                if (phone == null)
                    phone = snapshot.child("phone").getValue(String.class);
                if (phone != null)
                    inputPhone.setText(phone);

                String dbEmail = snapshot.child("email").getValue(String.class);
                if (dbEmail != null)
                    inputEmailEdit.setText(dbEmail);

                photoUrl = snapshot.child("photoUrl").getValue(String.class);
                if (photoUrl != null && !photoUrl.isEmpty()) {
                    Glide.with(this).load(photoUrl).circleCrop().into(imgProfile);
                }
            }
        });
    }

    private void uploadImageToFirebase(Uri imageUri) {
        if (documentId == null)
            return;

        StorageReference storageRef = FirebaseStorage.getInstance().getReference()
                .child("profile_pics/" + UUID.randomUUID().toString());

        storageRef.putFile(imageUri).addOnSuccessListener(taskSnapshot -> {
            storageRef.getDownloadUrl().addOnSuccessListener(uri -> {
                photoUrl = uri.toString();
                Glide.with(this).load(photoUrl).circleCrop().into(imgProfile);
                
                // Salvar a nova URL da foto imediatamente na DB
                Map<String, Object> photoUpdate = new HashMap<>();
                photoUpdate.put("photoUrl", photoUrl);
                databaseReference.child(documentId).updateChildren(photoUpdate).addOnCompleteListener(dbTask -> {
                    if (dbTask.isSuccessful()) {
                        Toast.makeText(this, "Foto atualizada com sucesso!", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(this, "Foto enviada, mas não foi possível atualizar o perfil.", Toast.LENGTH_SHORT).show();
                    }
                });
            });
        }).addOnFailureListener(e -> {
            Toast.makeText(this, "Falha no upload: " + e.getMessage(), Toast.LENGTH_LONG).show();
            android.util.Log.e("ProfileUpload", "Upload failed", e);
        });
    }

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

        String newName = inputName.getText().toString().trim();
        String newPhone = inputPhone.getText().toString().trim();
        String newEmail = inputEmailEdit.getText().toString().trim();

        if (TextUtils.isEmpty(newName)) {
            Toast.makeText(this, "Indique um nome.", Toast.LENGTH_SHORT).show();
            return;
        }

        Map<String, Object> updates = new HashMap<>();
        updates.put("displayName", newName);
        updates.put("phone", newPhone);
        updates.put("email", newEmail);
        if (photoUrl != null) {
            updates.put("photoUrl", photoUrl);
        }

        databaseReference.child(documentId).updateChildren(updates)
                .addOnSuccessListener(aVoid -> {
                    Toast.makeText(this, "Perfil atualizado!", Toast.LENGTH_SHORT).show();
                    Intent resultIntent = new Intent();
                    resultIntent.putExtra(MainActivity.EXTRA_DISPLAY_NAME, newName);
                    setResult(RESULT_OK, resultIntent);
                    finish();
                })
                .addOnFailureListener(
                        e -> Toast.makeText(this, "Falha ao atualizar perfil.", Toast.LENGTH_SHORT).show());
    }
}
