package com.example.nearbookssell;

import android.app.AlertDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Patterns;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

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

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import java.util.HashMap;
import java.util.Map;

public class LoginPage extends AppCompatActivity {

    Button btnSignUp, btnLogin;
    EditText inputEmail, inputPassword;

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

        // Initialize views
        btnSignUp = findViewById(R.id.btnSignUp);
        btnLogin = findViewById(R.id.btnLogin);
        inputEmail = findViewById(R.id.inputEmail);
        inputPassword = findViewById(R.id.inputPassword);

        // Navigate to SignUp Page
        btnSignUp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(LoginPage.this, SignUpPage.class));
            }
        });

        // Login Button Click
        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Get input values
                String email = inputEmail.getText().toString().trim();
                String password = inputPassword.getText().toString().trim();

                // Validate inputs
                if (!isValidEmail(email)) {
                    inputEmail.setError("Please enter a valid Gmail address");
                    return;
                }

                if (!isValidPassword(password)) {
                    inputPassword.setError("Password must be at least 6 characters");
                    return;
                }

                // Make network request
                String uri = "https://sjoybd.xyz/Nearbooks/login.php";
                StringRequest stringRequest = new StringRequest(Request.Method.POST, uri,
                        new Response.Listener<String>() {
                            @Override
                            public void onResponse(String response) {
                                if (response.contains("Valid Login")) {
                                    // Save email to SharedPreferences
                                    SharedPreferences sharedPreferences = getSharedPreferences("myApp", MODE_PRIVATE);
                                    SharedPreferences.Editor editor = sharedPreferences.edit();
                                    editor.putString("email", email);
                                    editor.apply();

                                    // Navigate to MainActivity
                                    startActivity(new Intent(LoginPage.this, MainActivity.class));
                                    finish();
                                } else {
                                    // Show server response error
                                    new AlertDialog.Builder(LoginPage.this)
                                            .setTitle("Server Response")
                                            .setMessage(response)
                                            .create().show();
                                }
                            }
                        },
                        new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError error) {
                                // Show Volley error
                                new AlertDialog.Builder(LoginPage.this)
                                        .setTitle("Error")
                                        .setMessage(error.getMessage())
                                        .create().show();
                            }
                        }) {
                    @Nullable
                    @Override
                    protected Map<String, String> getParams() throws AuthFailureError {
                        Map<String, String> map = new HashMap<>();
                        try {
                            map.put("email", myMethod.encryptData(email));
                            map.put("password", myMethod.encryptData(password));
                        } catch (Exception e) {
                            throw new RuntimeException(e);
                        }
                        map.put("key", myMethod.MY_KEY);
                        return map;
                    }
                };

                // Add request to Volley queue
                RequestQueue requestQueue = Volley.newRequestQueue(LoginPage.this);
                requestQueue.add(stringRequest);
            }
        });
    }

    // Email Validation
    private boolean isValidEmail(String email) {
        return email.endsWith("@gmail.com") && Patterns.EMAIL_ADDRESS.matcher(email).matches();
    }

    // Password Validation
    private boolean isValidPassword(String password) {
        return password.length() >= 6;
    }
}   aro dicchi