package com.example.punyaria;

import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.util.Patterns;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
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;

public class DataDiriActivity extends AppCompatActivity {

    private ImageView imageProfile;
    private static final int PICK_IMAGE_GALLERY = 1;

    private EditText editTextUsername, editTextNama, editTextEmail, editTextPhoneNumber, editTextTanggalLahir, editTextJenisKelamin, editTextAddress;
    private Button buttonSimpan;
    private SharedPreferences sharedPreferences;

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

        // Mendapatkan intent dan data yang diperlukan
        Intent intent = getIntent();
        boolean profileUpdated = intent.getBooleanExtra("profileUpdated", false);

        // Jika profil berhasil diperbarui, maka kita akan memulai transaksi fragment ke AkunFragment
        if (profileUpdated) {
            // Memulai transaksi fragment untuk menampilkan AkunFragment
            FragmentManager fragmentManager = getSupportFragmentManager(); // Menggunakan getSupportFragmentManager() karena menggunakan AppCompatActivity
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.replace(R.id.nav_host_fragment, new AkunFragment()); // Ganti R.id.container dengan ID dari container fragment di MainActivity Anda
            fragmentTransaction.commit();
        }
        ImageView headerImageView = findViewById(R.id.headerImageView);
        headerImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });

        imageProfile = findViewById(R.id.image_profile);
        TextView textEditPhoto = findViewById(R.id.text_edit_photo);
        editTextUsername = findViewById(R.id.editTextUsername);
        editTextNama = findViewById(R.id.editTextNama);
        editTextEmail = findViewById(R.id.editTextEmail);
        editTextPhoneNumber = findViewById(R.id.editTextPhoneNumber);
        editTextTanggalLahir = findViewById(R.id.editTextTanggalLahir);
        editTextJenisKelamin = findViewById(R.id.editTextJenisKelamin);
        editTextAddress = findViewById(R.id.editTextAddress);
        buttonSimpan = findViewById(R.id.buttonSimpan);

        textEditPhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showImagePickerDialog();
            }
        });

        String username = getUsername();

        DatabaseReference userRef = FirebaseDatabase.getInstance().getReference().child("users").child(username);
        userRef.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                if (dataSnapshot.exists()) {
                    User user = dataSnapshot.getValue(User.class);
                    if (user != null) {
                        editTextUsername.setText(user.getUsername());
                        editTextNama.setText(user.getNama());
                        editTextEmail.setText(user.getEmail());
                        editTextPhoneNumber.setText(user.getTelepon());
                        editTextTanggalLahir.setText(user.getTanggalLahir());
                        editTextJenisKelamin.setText(user.getJenisKelamin());
                        editTextAddress.setText(user.getAlamat());

                        String imageUrl = user.getProfileImageUrl();
                        if (imageUrl != null && !imageUrl.isEmpty()) {
                            Glide.with(getApplicationContext())
                                    .load(imageUrl)
                                    .transform(new CircleCrop())
                                    .placeholder(R.drawable.ic_profil)
                                    .error(R.drawable.ic_profil)
                                    .into(imageProfile);
                        }
                    }
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                Toast.makeText(getApplicationContext(), "Gagal memuat data: " + databaseError.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });

        // Hapus setEnabled(false) untuk editTextPhoneNumber
        // editTextPhoneNumber.setEnabled(false);

        buttonSimpan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                simpanData();
            }
        });
    }

    private String getUsername() {
        SharedPreferences sharedPreferences = getSharedPreferences("loginPrefs", MODE_PRIVATE);
        return sharedPreferences.getString("username", null);
    }

    private void showImagePickerDialog() {
        Intent pickIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        pickIntent.setType("image/*");

        startActivityForResult(pickIntent, PICK_IMAGE_GALLERY);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            if (requestCode == PICK_IMAGE_GALLERY && data != null) {
                Uri selectedImageUri = data.getData();
                if (selectedImageUri != null) {
                    Glide.with(getApplicationContext())
                            .load(selectedImageUri)
                            .transform(new CircleCrop())
                            .placeholder(R.drawable.ic_profil)
                            .error(R.drawable.ic_profil)
                            .into(imageProfile);

                    saveImageToDatabase(selectedImageUri);
                }
            }
        }
    }

    private void saveImageToDatabase(Uri imageUrl) {
        String username = getUsername();

        DatabaseReference userRef = FirebaseDatabase.getInstance().getReference().child("users").child(username);

        userRef.child("profileImageUrl").setValue(imageUrl.toString())
                .addOnSuccessListener(new OnSuccessListener<Void>() {
                    @Override
                    public void onSuccess(Void aVoid) {
                        // Periksa jika username adalah "uptd_ppajember21"
                        String username = getUsername(); // Mendapatkan username
                        if (username != null && username.equals("uptd_ppajember21")) {
                            // Jika username adalah "uptd_ppajember21", arahkan pengguna ke AdminActivity
                            Toast.makeText(getApplicationContext(), "Foto Profil berhasil diperbarui", Toast.LENGTH_SHORT).show();
                            Intent intent = new Intent(getApplicationContext(), AdminActivity.class);
                            startActivity(intent);
                        } else {
                            // Jika bukan, arahkan pengguna ke MainActivity
                            Toast.makeText(getApplicationContext(), "Foto Profil berhasil diperbarui", Toast.LENGTH_SHORT).show();
                            Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                            intent.putExtra("selectedFragment", R.id.navigation_account); // ID navigasi untuk BerandaFragment
                            startActivity(intent);
                        }
                        finish(); // Selesaikan aktivitas saat ini
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Toast.makeText(getApplicationContext(), "Gagal memperbarui foto profil: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });
    }

    private void simpanData() {
        final String username = editTextUsername.getText().toString().trim();
        final String nama = editTextNama.getText().toString().trim();
        final String email = editTextEmail.getText().toString().trim();
        final String telepon = editTextPhoneNumber.getText().toString().trim();
        final String tanggalLahir = editTextTanggalLahir.getText().toString().trim();
        final String jenisKelamin = editTextJenisKelamin.getText().toString().trim();
        final String alamat = editTextAddress.getText().toString().trim();

        // Validasi nomor telepon
        if (!telepon.isEmpty() && !telepon.matches("\\d{10,15}")) {
            Toast.makeText(getApplicationContext(), "Nomor telepon harus terdiri dari 10-15 digit angka", Toast.LENGTH_SHORT).show();
            return;
        }

        // Validasi email
        if (!email.isEmpty() && !Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
            Toast.makeText(getApplicationContext(), "Email tidak valid", Toast.LENGTH_SHORT).show();
            return;
        }

        // Cek apakah nomor telepon sudah terdaftar
        DatabaseReference usersRef = FirebaseDatabase.getInstance().getReference().child("users");
        usersRef.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                boolean phoneExists = false;
                for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                    User user = snapshot.getValue(User.class);
                    if (user != null && telepon.equals(user.getTelepon()) && !username.equals(user.getUsername())) {
                        phoneExists = true;
                        break;
                    }
                }

                if (phoneExists) {
                    Toast.makeText(getApplicationContext(), "Nomor Telepon sudah terdaftar dengan akun lain", Toast.LENGTH_SHORT).show();
                } else {
                    // Simpan data ke Firebase
                    DatabaseReference userRef = FirebaseDatabase.getInstance().getReference().child("users").child(username);

                    // Set data ke Firebase, tetap menyimpan nilai kosong jika input kosong
                    userRef.child("nama").setValue(nama.isEmpty() ? "" : nama);
                    userRef.child("email").setValue(email.isEmpty() ? "" : email);
                    userRef.child("telepon").setValue(telepon.isEmpty() ? "" : telepon);
                    userRef.child("tanggalLahir").setValue(tanggalLahir.isEmpty() ? "" : tanggalLahir);
                    userRef.child("jenisKelamin").setValue(jenisKelamin.isEmpty() ? "" : jenisKelamin);
                    userRef.child("alamat").setValue(alamat.isEmpty() ? "" : alamat);

                    // Success message
                    Toast.makeText(getApplicationContext(), "Data berhasil disimpan", Toast.LENGTH_SHORT).show();

                    // Update gambar profil di AkunFragment setelah data berhasil disimpan
                    Intent resultIntent = new Intent();
                    resultIntent.putExtra("profileUpdated", true);
                    setResult(RESULT_OK, resultIntent);
                    finish();
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                Toast.makeText(getApplicationContext(), "Gagal menyimpan data " + databaseError.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }

}
