package com.example.punyaria;

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

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.EditText;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

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.Query;
import com.google.firebase.database.ValueEventListener;

public class LoginActivity extends AppCompatActivity {

    private boolean isPasswordVisible = false;
    private EditText passwordEditText, editTextUsername;

    private ImageView imageViewPasswordVisibility;
    private boolean isPasswordVisible1 = false;
    private Button buttonLogin;

    // Tambahkan shared preferences
    private SharedPreferences sharedPreferences;

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

        // Inisialisasi EditText dan ImageView
        passwordEditText = findViewById(R.id.editTextPassword);
        imageViewPasswordVisibility = findViewById(R.id.imageViewPasswordVisibility);
        imageViewPasswordVisibility.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Ganti ikon dan visibility password
                togglePasswordVisibility(passwordEditText, imageViewPasswordVisibility, isPasswordVisible1);
                isPasswordVisible1 = !isPasswordVisible1; // Update status visibilitas
            }
        });

        // Atur icon pada awalnya
        setIconVisibility(imageViewPasswordVisibility, isPasswordVisible1);
        editTextUsername = findViewById(R.id.editTextUsername);

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

        // Periksa status login saat aplikasi dimulai
        if (isLoggedIn()) {
            String username = getUsername();
            if (username != null) {
                loginSuccess(username);
            }
        }

        // Inisialisasi button login
        buttonLogin = findViewById(R.id.buttonLogin);

        // Menambahkan listener klik pada tombol login
        buttonLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String username = editTextUsername.getText().toString().trim();
                String password = passwordEditText.getText().toString().trim();

                if (username.isEmpty() || password.isEmpty()) {
                    // Jika ada data yang masih kosong
                    Toast.makeText(getApplicationContext(), "Username atau password tidak boleh kosong", Toast.LENGTH_SHORT).show();
                } else {
                    // Proses login
                    DatabaseReference usersRef = FirebaseDatabase.getInstance().getReference().child("users").child(username);

                    usersRef.addListenerForSingleValueEvent(new ValueEventListener() {
                        @Override
                        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                            if (dataSnapshot.exists()) {
                                // Pengguna ditemukan berdasarkan username
                                User user = dataSnapshot.getValue(User.class);
                                if (user != null && user.getPassword().equals(password)) {
                                    // Login berhasil
                                    loginSuccess(username);
                                } else {
                                    // Password salah
                                    Toast.makeText(getApplicationContext(), "Username atau password salah", Toast.LENGTH_SHORT).show();
                                }
                            } else {
                                // Pengguna tidak ditemukan berdasarkan username, coba mencari berdasarkan nomor telepon
                                DatabaseReference usersByPhoneRef = FirebaseDatabase.getInstance().getReference().child("users");
                                Query query = usersByPhoneRef.orderByChild("telepon").equalTo(username);
                                query.addListenerForSingleValueEvent(new ValueEventListener() {
                                    @Override
                                    public void onDataChange(@NonNull DataSnapshot snapshot) {
                                        if (snapshot.exists()) {
                                            for (DataSnapshot userSnapshot : snapshot.getChildren()) {
                                                User user = userSnapshot.getValue(User.class);
                                                if (user != null && user.getPassword().equals(password)) {
                                                    // Login berhasil
                                                    loginSuccess(user.getUsername());
                                                    return;
                                                }
                                            }
                                            // Password salah
                                            Toast.makeText(getApplicationContext(), "Username atau password salah", Toast.LENGTH_SHORT).show();
                                        } else {
                                            // Pengguna tidak ditemukan berdasarkan nomor telepon
                                            Toast.makeText(getApplicationContext(), "Username atau nomor telepon tidak ditemukan", Toast.LENGTH_SHORT).show();
                                        }
                                    }

                                    @Override
                                    public void onCancelled(@NonNull DatabaseError error) {
                                        // Error handling
                                        Toast.makeText(getApplicationContext(), "Gagal memproses data: " + error.getMessage(), Toast.LENGTH_SHORT).show();
                                    }
                                });
                            }
                        }

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

    // Method untuk login berhasil
    private void loginSuccess(String username) {
        if (username.equals("uptd_ppajember21")) {
            Intent intent = new Intent(LoginActivity.this, AdminActivity.class);
            startActivity(intent);
        } else {
            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
            startActivity(intent);
        }
        saveLoginStatus(true);
        saveUsername(username);
        finish();
    }

    // Fungsi untuk menyimpan status login ke shared preferences
    private void saveLoginStatus(boolean isLoggedIn) {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putBoolean("isLoggedIn", isLoggedIn);
        editor.apply();
    }

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

    // Fungsi untuk memeriksa status login dari shared preferences
    private boolean isLoggedIn() {
        return sharedPreferences.getBoolean("isLoggedIn", false);
    }

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

    public void goToRegister(View view) {
        Intent intent = new Intent(this, RegisterActivity.class);
        startActivity(intent);
    }

    public void goToForgotPassword(View view) {
        Intent intent = new Intent(this, ForgotPasswordActivity.class);
        startActivity(intent);
    }

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

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

    private void setIconVisibility(ImageView imageView, boolean isVisible) {
        if (isVisible) {
            imageView.setImageResource(R.drawable.ic_visibility_on);
        } else {
            imageView.setImageResource(R.drawable.ic_visibility_off);
        }
    }
}
