package com.example.punyaria;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

public class GantiPasswordActivity extends AppCompatActivity {

    private EditText editTextPasswordAktif, editTextPasswordBaru, editTextKpasswordBaru;
    private Button buttonSimpan;

    private ImageView imageViewAPasswordVisibility;
    private ImageView imageViewPasswordVisibility;
    private ImageView imageViewKPasswordVisibility;

    // Tambahkan shared preferences
    private SharedPreferences sharedPreferences;

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

        editTextPasswordAktif = findViewById(R.id.editTextPasswordAktif);
        editTextPasswordBaru = findViewById(R.id.editTextPasswordBaru);
        editTextKpasswordBaru = findViewById(R.id.editTextKpasswordBaru);
        imageViewAPasswordVisibility = findViewById(R.id.imageViewAPasswordVisibility);
        imageViewPasswordVisibility = findViewById(R.id.imageViewPasswordVisibility);
        imageViewKPasswordVisibility = findViewById(R.id.imageViewKPasswordVisibility);
        buttonSimpan = findViewById(R.id.buttonSimpan);

        // Atur onClickListener untuk imageView editTextPasswordAktif
        imageViewAPasswordVisibility.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Ganti ikon dan visibility password
                togglePasswordVisibility(editTextPasswordAktif, imageViewAPasswordVisibility);
            }
        });

        // Atur onClickListener untuk imageView editTextPasswordBaru
        imageViewPasswordVisibility.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Ganti ikon dan visibility password
                togglePasswordVisibility(editTextPasswordBaru, imageViewPasswordVisibility);
            }
        });

        // Atur onClickListener untuk imageView editTextKPasswordBaru
        imageViewKPasswordVisibility.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Ganti ikon dan visibility password
                togglePasswordVisibility(editTextKpasswordBaru, imageViewKPasswordVisibility);
            }
        });

        // Inisialisasi shared preferences
        sharedPreferences = getSharedPreferences("loginPrefs", MODE_PRIVATE);

        // Menambahkan listener klik pada tombol Simpan
        buttonSimpan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                simpanPasswordBaru();
            }
        });

        ImageView headerImageView = findViewById(R.id.headerImageView);
        headerImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
    }

    private void simpanPasswordBaru() {
        String passwordAktif = editTextPasswordAktif.getText().toString().trim();
        String passwordBaru = editTextPasswordBaru.getText().toString().trim();
        String kPasswordBaru = editTextKpasswordBaru.getText().toString().trim();

        if (TextUtils.isEmpty(passwordAktif) || TextUtils.isEmpty(passwordBaru) || TextUtils.isEmpty(kPasswordBaru)) {
            // Jika ada input yang masih kosong
            Toast.makeText(this, "Semua input harus diisi", Toast.LENGTH_SHORT).show();
            return;
        }

        if (!passwordBaru.equals(kPasswordBaru)) {
            // Jika password baru tidak cocok dengan konfirmasi password baru
            Toast.makeText(this, "Password baru dan konfirmasi password baru tidak cocok", Toast.LENGTH_SHORT).show();
            return;
        }

        if (!passwordBaru.matches("^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[+×÷=/_€£¥₩!@#$%^&*()':;,?`~<>{}¡¿])(?=\\S+$).{8,}$")) {
            // Jika password tidak memenuhi kriteria
            Toast.makeText(getApplicationContext(), "Password harus terdiri dari minimal 8 karakter berisi kombinasi huruf kapital dan kecil, angka, dan simbol", Toast.LENGTH_SHORT).show();
            return;
        }

        // Dapatkan username dari shared preferences
        String username = getUsername();

        // Perbarui password di Firebase Realtime Database
        updatePasswordInDatabase(username, passwordBaru);

        // Simpan password baru ke shared preferences
        savePasswordBaru(passwordBaru);

        // Tampilkan pesan sukses
        Toast.makeText(this, "Password berhasil diubah", Toast.LENGTH_SHORT).show();

        // Kembali ke halaman sebelumnya atau lakukan tindakan lain sesuai kebutuhan
        finish();
    }


    // Fungsi untuk menyimpan password baru ke shared preferences
    private void savePasswordBaru(String passwordBaru) {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString("password", passwordBaru);
        editor.apply();
    }

    // Fungsi untuk mendapatkan password aktif dari shared preferences
    private String getPasswordAktif() {
        // Menggunakan key "password" untuk mengambil password dari shared preferences
        return sharedPreferences.getString("password", "");
    }

    // Fungsi untuk mendapatkan username dari shared preferences
    private String getUsername() {
        // Menggunakan key "username" untuk mengambil username dari shared preferences
        return sharedPreferences.getString("username", "");
    }

    // Fungsi untuk memperbarui password di Firebase Realtime Database
    private void updatePasswordInDatabase(String username, String passwordBaru) {
        DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child("users").child(username);
        databaseReference.child("password").setValue(passwordBaru);
    }

    private void togglePasswordVisibility(EditText editText, ImageView imageView) {
        boolean isPasswordVisible = editText.getTransformationMethod() instanceof PasswordTransformationMethod;

        if (isPasswordVisible) {
            // Jika password terlihat, sembunyikan dan ganti ikon
            editText.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
            imageView.setImageResource(R.drawable.ic_visibility_on);
        } else {
            // Jika password tersembunyi, tampilkan dan ganti ikon
            editText.setTransformationMethod(PasswordTransformationMethod.getInstance());
            imageView.setImageResource(R.drawable.ic_visibility_off);
        }
    }
}
