package com.example.punyaria;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Layout;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
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 ForgotPasswordActivity extends AppCompatActivity {

    private Button buttonLanjutkan;
    private EditText editTextUsername, editTextUmur;
    private DatabaseReference usersRef;
    private int selectedDay, selectedMonth, selectedYear;

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

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

        // Inisialisasi button
        buttonLanjutkan = findViewById(R.id.buttonLanjutkan);
        editTextUsername = findViewById(R.id.editTextUsername);
        editTextUmur = findViewById(R.id.editTextUmur);

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

        // Menambahkan listener klik pada tombol
        buttonLanjutkan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Mendapatkan username dan tanggal lahir dari input pengguna
                String username = editTextUsername.getText().toString().trim();
                String tanggalLahir = editTextUmur.getText().toString().trim();

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

                // Simpan username ke SharedPreferences
                SharedPreferences sharedPreferences = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.putString("username", username);
                editor.apply();

                // Mengecek apakah username ada di database
                usersRef.child(username).addListenerForSingleValueEvent(new ValueEventListener() {
                    @Override
                    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                        if (dataSnapshot.exists()) {
                            // Username ditemukan, sekarang periksa tanggal lahir
                            String tanggalLahirDatabase = dataSnapshot.child("tanggalLahir").getValue(String.class);
                            if (tanggalLahir.equals(tanggalLahirDatabase)) {
                                // Tanggal lahir cocok, lanjut ke ResetPasswordActivity
                                Intent intent = new Intent(ForgotPasswordActivity.this, ResetPasswordActivity.class);
                                startActivity(intent);
                            } else {
                                Toast.makeText(ForgotPasswordActivity.this, "Tanggal lahir salah", Toast.LENGTH_SHORT).show();
                            }
                        } else {
                            // Username tidak ditemukan di database
                            Toast.makeText(ForgotPasswordActivity.this, "Username tidak ditemukan", Toast.LENGTH_SHORT).show();
                        }
                    }

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

        // Menambahkan listener klik pada editTextTanggalLahir
        editTextUmur.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDatePickerDialog(ForgotPasswordActivity.this);
            }
        });
    }

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