package com.example.nearbookssell;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Base64;
import android.util.Patterns;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
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 com.github.dhaval2404.imagepicker.ImagePicker;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import kotlin.Unit;
import kotlin.jvm.functions.Function1;

public class SignUpPage extends AppCompatActivity {

    ImageView profileImage;
    TextView choosePhoto;
    EditText userName, userEmail, userPassword;
    Button registerBTN, btnLoginPage;

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

        // Initialize views
        profileImage = findViewById(R.id.profileImage);
        choosePhoto = findViewById(R.id.choosePhoto);
        userName = findViewById(R.id.userName);
        userEmail = findViewById(R.id.userEmail);
        userPassword = findViewById(R.id.userPassword);
        registerBTN = findViewById(R.id.registerBTN);
        btnLoginPage = findViewById(R.id.btnLoginPage);

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

        // Register Button Click
        registerBTN.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Get input values
                String name = userName.getText().toString().trim();
                String email = userEmail.getText().toString().trim();
                String password = userPassword.getText().toString().trim();

                // Validate inputs
                if (name.isEmpty()) {
                    userName.setError("Name is required");
                    return;
                }

                if (!isValidEmail(email)) {
                    userEmail.setError("Please enter a valid Gmail address");
                    return;
                }

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

                // Convert profile image to Base64
                BitmapDrawable bitmapDrawable = (BitmapDrawable) profileImage.getDrawable();
                Bitmap bitmap = bitmapDrawable.getBitmap();
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 50, byteArrayOutputStream);
                byte[] imageBytes = byteArrayOutputStream.toByteArray();
                String image = Base64.encodeToString(imageBytes, Base64.DEFAULT);

                // Make network request
                String uri = "https://sjoybd.xyz/Nearbooks/signup.php";
                StringRequest stringRequest = new StringRequest(Request.Method.POST, uri,
                        new Response.Listener<String>() {
                            @Override
                            public void onResponse(String response) {
                                if (response.contains("Signup Success")) {
                                    // 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(SignUpPage.this, MainActivity.class));
                                    finish();
                                } else {
                                    // Show server response error
                                    new AlertDialog.Builder(SignUpPage.this)
                                            .setTitle("Server Response")
                                            .setMessage(response)
                                            .create().show();
                                }
                            }
                        },
                        new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError error) {
                                // Show Volley error
                                new AlertDialog.Builder(SignUpPage.this)
                                        .setTitle("Error")
                                        .setMessage(error.getMessage())
                                        .create().show();
                            }
                        }) {
                    @Nullable
                    @Override
                    protected Map<String, String> getParams() throws AuthFailureError {
                        Map<String, String> map = new HashMap<>();
                        map.put("name", name);
                        try {
                            map.put("email", myMethod.encryptData(email));
                            map.put("password", myMethod.encryptData(password));
                        } catch (Exception e) {
                            throw new RuntimeException(e);
                        }
                        map.put("image", image);
                        map.put("key", myMethod.MY_KEY);
                        return map;
                    }
                };

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

        // Image Picker Launcher
        ActivityResultLauncher<Intent> launcher =
                registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
                        new ActivityResultCallback<ActivityResult>() {
                            @Override
                            public void onActivityResult(ActivityResult result) {
                                if (result.getResultCode() == Activity.RESULT_OK) {
                                    Intent intent = result.getData();
                                    Uri uri = intent.getData();
                                    try {
                                        Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
                                        profileImage.setImageBitmap(bitmap);
                                    } catch (IOException e) {
                                        throw new RuntimeException(e);
                                    }
                                }
                            }
                        });

        // Choose Photo Button Click
        choosePhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ImagePicker.with(SignUpPage.this)
                        .maxResultSize(1000, 1000)
                        .compress(1024)
                        .createIntent(new Function1<Intent, Unit>() {
                            @Override
                            public Unit invoke(Intent intent) {
                                launcher.launch(intent);
                                return null;
                            }
                        });
            }
        });
    }

    // 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 code dicchi wait