package com.example.punyaria;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

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

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 ResetPasswordActivity extends AppCompatActivity {

    private EditText editTextPasswordBaru;
    private EditText editTextKPasswordBaru;
    private Button buttonSimpan;
    private ImageView imageViewPasswordVisibility;
    private ImageView imageViewKPasswordVisibility;
    private DatabaseReference usersRef;

    private boolean isPasswordVisible1 = false; // Untuk editTextPasswordBaru
    private boolean isPasswordVisible2 = false; // Untuk editTextKPasswordBaru

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

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

        // Inisialisasi EditText, Button, dan ImageView
        editTextPasswordBaru = findViewById(R.id.editTextPasswordBaru);
        editTextKPasswordBaru = findViewById(R.id.editTextKPasswordBaru);
        buttonSimpan = findViewById(R.id.buttonSimpan);
        imageViewPasswordVisibility = findViewById(R.id.imageViewPasswordVisibility);
        imageViewKPasswordVisibility = findViewById(R.id.imageViewKPasswordVisibility);

        // Mendapatkan referensi ke tabel "users" di Firebase Database
        usersRef = FirebaseDatabase.getInstance().getReference().child("users");

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

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

        // Atur icon pada awalnya
        setIconVisibility(imageViewPasswordVisibility, isPasswordVisible1);
        setIconVisibility(imageViewKPasswordVisibility, isPasswordVisible2);

        // Menambahkan listener klik pada buttonSimpan
        buttonSimpan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String passwordBaru = editTextPasswordBaru.getText().toString().trim();
                String kPasswordBaru = editTextKPasswordBaru.getText().toString().trim();

                // Memastikan kedua input tidak kosong
                if (TextUtils.isEmpty(passwordBaru) || TextUtils.isEmpty(kPasswordBaru)) {
                    Toast.makeText(ResetPasswordActivity.this, "Isi semua field", Toast.LENGTH_SHORT).show();
                    return;
                }

                // Memastikan kedua password baru sesuai
                if (!passwordBaru.equals(kPasswordBaru)) {
                    Toast.makeText(ResetPasswordActivity.this, "Password tidak sesuai", Toast.LENGTH_SHORT).show();
                    return;
                }

                // Memastikan password baru memenuhi kriteria
                if (!isValidPassword(passwordBaru)) {
                    Toast.makeText(ResetPasswordActivity.this, "Password harus terdiri dari minimal 8 karakter berisi kombinasi huruf kapital dan kecil, angka, dan simbol", Toast.LENGTH_SHORT).show();
                    return;
                }

                // Memperbarui password di database
                updatePassword(passwordBaru);
            }
        });
    }

    // Method untuk memperbarui password di database
    private void updatePassword(final String newPassword) {
        // Mendapatkan username dari SharedPreferences
        String username = getSharedPreferences("MyPrefs", MODE_PRIVATE).getString("username", "");

        // Memperbarui password di database
        usersRef.child(username).addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                dataSnapshot.getRef().child("password").setValue(newPassword);
                Toast.makeText(ResetPasswordActivity.this, "Password berhasil diperbarui", Toast.LENGTH_SHORT).show();

                // Setelah berhasil, masuk ke LoginActivity
                Intent intent = new Intent(ResetPasswordActivity.this, LoginActivity.class);
                startActivity(intent);

                // Hapus halaman ResetPasswordActivity dari tumpukan activity
                finish();
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                // Error handling
                Toast.makeText(ResetPasswordActivity.this, "Gagal memperbarui password: " + databaseError.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    // Method untuk memeriksa apakah password baru memenuhi kriteria
    private boolean isValidPassword(String password) {
        // Pola untuk memeriksa password
        String passwordPattern = "^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[+×÷=/_€£¥₩!@#$%^&*()':;,?`~<>{}¡¿])(?=\\S+$).{8,}$";
        return password.matches(passwordPattern);
    }

    // Method untuk mengubah visibilitas password
    private void togglePasswordVisibility(EditText editText, ImageView imageView, boolean isPasswordVisible) {
        if (isPasswordVisible) {
            // Jika password terlihat, sembunyikan dan ganti ikon
            editText.setTransformationMethod(android.text.method.PasswordTransformationMethod.getInstance());
        } else {
            // Jika password tersembunyi, tampilkan dan ganti ikon
            editText.setTransformationMethod(android.text.method.HideReturnsTransformationMethod.getInstance());
        }

        // Update icon
        setIconVisibility(imageView, !isPasswordVisible);
    }

    // Method untuk mengatur ikon visibilitas password
    private void setIconVisibility(ImageView imageView, boolean isVisible) {
        if (isVisible) {
            imageView.setImageResource(R.drawable.ic_visibility_on);
        } else {
            imageView.setImageResource(R.drawable.ic_visibility_off);
        }
    }
}
