package com.example.punyaria;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Layout;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.text.style.AlignmentSpan;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.NumberPicker;
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;

import java.util.Calendar;

public class RegisterActivity extends AppCompatActivity {

    private boolean isPasswordVisible = false;
    private EditText editTextUsername, editTextPhoneNumber, editTextAddress;
    private EditText passwordEditText;
    private EditText kPasswordEditText; // Tambahkan EditText untuk konfirmasi password

    private ImageView imageViewPasswordVisibility;
    private ImageView imageViewKPasswordVisibility;

    private boolean isPasswordVisible1 = false;
    private boolean isPasswordVisible2 = false;
    private EditText editTextUmur; // Tambahkan EditText untuk tanggal lahir
    private EditText editTextJenisKelamin; // Tambahkan EditText untuk jenis kelamin

    private int selectedDay, selectedMonth, selectedYear;

    private Button buttonRegister;


    private DatabaseReference database;

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

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

        // Inisialisasi EditText dan ImageView
        passwordEditText = findViewById(R.id.editTextPassword);
        imageViewPasswordVisibility = findViewById(R.id.imageViewPasswordVisibility);

        kPasswordEditText = findViewById(R.id.editTextKPassword);
        imageViewKPasswordVisibility = findViewById(R.id.imageViewKPasswordVisibility);

        // Atur onClickListener untuk imageView editTextPasswordBaru
        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 onClickListener untuk imageView editTextKPasswordBaru
        imageViewKPasswordVisibility.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Ganti ikon dan visibility password
                togglePasswordVisibility(kPasswordEditText, imageViewKPasswordVisibility, isPasswordVisible2);
                isPasswordVisible2 = !isPasswordVisible2; // Update status visibilitas
            }
        });

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

        editTextUsername = findViewById(R.id.editTextUsername);
        editTextPhoneNumber = findViewById(R.id.editTextPhoneNumber);
        editTextAddress = findViewById(R.id.editTextAddress);
        editTextUmur = findViewById(R.id.editTextUmur);
        editTextJenisKelamin = findViewById(R.id.editTextJenisKelamin);

        database = FirebaseDatabase.getInstance().getReferenceFromUrl("https://j-counseling-default-rtdb.firebaseio.com/");

        // Menambahkan listener klik pada EditText jenis kelamin
        editTextJenisKelamin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showGenderOptionsDialog();
            }
        });

        // Menambahkan listener klik pada tombol register
        buttonRegister = findViewById(R.id.buttonRegister);
        buttonRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String username = editTextUsername.getText().toString().trim();
                String telepon = editTextPhoneNumber.getText().toString().trim();
                String tanggalLahir = editTextUmur.getText().toString().trim();
                String jenisKelamin = editTextJenisKelamin.getText().toString().trim();
                String alamat = editTextAddress.getText().toString().trim();
                String password = passwordEditText.getText().toString().trim();
                String kPassword = kPasswordEditText.getText().toString().trim();

                if (username.isEmpty() || telepon.isEmpty() || tanggalLahir.isEmpty() || jenisKelamin.isEmpty() || alamat.isEmpty() || password.isEmpty() || kPassword.isEmpty()) {
                    // Jika ada data yang masih kosong
                    Toast.makeText(getApplicationContext(), "Ada data yang masih kosong", Toast.LENGTH_SHORT).show();
                }else if (!telepon.matches("\\d{10,15}")) {
                // Jika nomor telepon tidak memenuhi kriteria
                Toast.makeText(getApplicationContext(), "Nomor Telepon minimal terdiri dari 10 digit angka", Toast.LENGTH_SHORT).show();
                }else if (!password.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();
                } else if (!password.equals(kPassword)) {
                    // Jika password tidak sesuai dengan konfirmasi password
                    Toast.makeText(getApplicationContext(), "Password tidak cocok", Toast.LENGTH_SHORT).show();
                } else if (username.contains(".") || username.contains("#") || username.contains("$") || username.contains("[") || username.contains("]")) {
                    Toast.makeText(getApplicationContext(), "Username tidak boleh mengandung '.', '#', '$', '[', atau ']'", Toast.LENGTH_SHORT).show();
                } else {
                    // Semua data telah terisi, simpan ke dalam tabel user
                    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 existingUser = snapshot.getValue(User.class);
                                if (existingUser != null && existingUser.getTelepon().equals(telepon)) {
                                    phoneExists = true;
                                    break;
                                }
                            }
                            if (phoneExists) {
                                Toast.makeText(getApplicationContext(), "Nomor telepon telah terdaftar", Toast.LENGTH_SHORT).show();
                            } else if (dataSnapshot.hasChild(username)) {
                                Toast.makeText(getApplicationContext(), "Username telah terdaftar", Toast.LENGTH_SHORT).show();
                            } else {
                                // Simpan data ke dalam tabel user
                                User newUser = new User(username, telepon, tanggalLahir, jenisKelamin, alamat, password);
                                usersRef.child(username).setValue(newUser);
                                Toast.makeText(getApplicationContext(), "Registrasi berhasil", Toast.LENGTH_SHORT).show();

                                // Pindahkan pengguna ke halaman login
                                Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
                                startActivity(intent);
                                finish(); // Optional, untuk menutup activity saat ini
                            }
                        }

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


        // Menambahkan listener klik pada EditText tanggal lahir untuk menampilkan DatePickerDialog
        editTextUmur.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDatePickerDialog(RegisterActivity.this);
            }
        });
    }


    // Method untuk menampilkan DatePickerDialog
    private void showDatePickerDialog(Context context) {
        final View dialogView = LayoutInflater.from(context).inflate(R.layout.dialog_date_picker, null);
        final NumberPicker dayPicker = dialogView.findViewById(R.id.dayPicker);
        final NumberPicker monthPicker = dialogView.findViewById(R.id.monthPicker);
        final NumberPicker yearPicker = dialogView.findViewById(R.id.yearPicker);

        // Initialize day picker
        dayPicker.setMinValue(1);
        dayPicker.setMaxValue(31);
        // Initialize month picker
        monthPicker.setMinValue(1);
        monthPicker.setMaxValue(12);
        // Initialize year picker
        int currentYear = Calendar.getInstance().get(Calendar.YEAR);
        yearPicker.setMinValue(currentYear - 100); // Adjust as needed
        yearPicker.setMaxValue(currentYear);

        // Set initial values
        dayPicker.setValue(selectedDay);
        monthPicker.setValue(selectedMonth);
        yearPicker.setValue(selectedYear);

        // Create a SpannableString to set title color and alignment
        String title = "Tanggal Lahir";
        SpannableString spannableString = new SpannableString(title);

// Set color
        spannableString.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.grey)), 0, title.length(), 0);

// Set alignment
        spannableString.setSpan(new AlignmentSpan.Standard(Layout.Alignment.ALIGN_CENTER), 0, title.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
        alertDialogBuilder.setView(dialogView)
                .setTitle(spannableString)
                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        selectedDay = dayPicker.getValue();
                        selectedMonth = monthPicker.getValue();
                        selectedYear = yearPicker.getValue();
                        editTextUmur.setText(String.format("%02d/%02d/%04d", selectedDay, selectedMonth, selectedYear));
                    }
                })
                .setNegativeButton("Batal", null)
                .show();
    }

    // Method untuk menampilkan dialog pilihan jenis kelamin
    private void showGenderOptionsDialog() {
        // Membuat instance dari GenderDialog
        GenderDialog genderDialog = new GenderDialog(RegisterActivity.this, new GenderDialog.GenderDialogListener() {
            @Override
            public void onGenderSelected(String gender) {
                // Ketika jenis kelamin dipilih, atur teks pada EditText jenis kelamin
                editTextJenisKelamin.setText(gender);
            }
        });
        // Menampilkan dialog
        genderDialog.show();
    }

    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);
        }
    }
}
