package com.nurulwafa.nufakuproject;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.google.firebase.messaging.FirebaseMessaging;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

    private EditText edtEmailOrNIS;
    private EditText edtPassword;
    private Button btnLogin;
    private boolean isPasswordVisible = false;

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

        edtEmailOrNIS = findViewById(R.id.email);
        edtPassword = findViewById(R.id.password);
        btnLogin = findViewById(R.id.loginButton);
        ImageView togglePasswordVisibility = findViewById(R.id.togglePasswordVisibility);

        togglePasswordVisibility.setOnClickListener(v -> {
            if (isPasswordVisible) {
                edtPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                togglePasswordVisibility.setImageResource(R.drawable.ic_eye_closed);
                isPasswordVisible = false;
            } else {
                edtPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                togglePasswordVisibility.setImageResource(R.drawable.ic_eye_open);
                isPasswordVisible = true;
            }
            edtPassword.setSelection(edtPassword.getText().length());
        });

        btnLogin.setOnClickListener(view -> {
            String inputEmailOrNIS = edtEmailOrNIS.getText().toString().trim();
            String inputPassword = edtPassword.getText().toString().trim();

            if (inputEmailOrNIS.isEmpty() || inputPassword.isEmpty()) {
                Toast.makeText(MainActivity.this, "Email/NIS dan Password tidak boleh kosong!", Toast.LENGTH_SHORT).show();
                return;
            }

            new Thread(() -> {
                try {
                    String urlLogin = ApiHelper.getBaseUrl() + "loginWaliSantri";
                    URL url = new URL(urlLogin);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("POST");
                    conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
                    conn.setDoOutput(true);
                    conn.setDoInput(true);

                    JSONObject jsonParam = new JSONObject();
                    jsonParam.put("email_or_NIS", inputEmailOrNIS);
                    jsonParam.put("password", inputPassword);

                    OutputStream os = conn.getOutputStream();
                    os.write(jsonParam.toString().getBytes("UTF-8"));
                    os.close();

                    int responseCode = conn.getResponseCode();
                    if (responseCode == HttpURLConnection.HTTP_OK) {
                        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                        StringBuilder sb = new StringBuilder();
                        String line;
                        while ((line = in.readLine()) != null) {
                            sb.append(line);
                        }
                        in.close();

                        // Tambahkan debug di sini
                        String responseData = sb.toString();
                        // Log.d("API_RESPONSE", responseData);
                        JSONObject responseJson = new JSONObject(responseData);

                        String status = responseJson.getString("status");

                        runOnUiThread(() -> {
                            if (status.equals("success") || status.equals("true")) {
                                try {
                                    JSONObject santri = responseJson.getJSONObject("santri");
                                    String idSantri = santri.getString("id_santri");

                                    JSONObject waliSantri = responseJson.getJSONObject("wali_santri");
                                    String idWaliSantri = waliSantri.getString("id_wali_santri");
                                    String kondisiKesehatan = waliSantri.optString("kondisi_kesehatan");
                                    // Log.d("Kesehatan", "Login - kondisi dari API: " + kondisiKesehatan);
                                    // Log.d("LOGIN_ID_SANTRI", "ID Santri dari API: " + idSantri);


                                    // SharedPreferences DI SINI — di thread utama
                                    SharedPreferences preferences = getSharedPreferences("santri", MODE_PRIVATE);
                                    SharedPreferences.Editor editor = preferences.edit();
                                    editor.putString("id_santri", idSantri);
                                    editor.putString("kondisi_kesehatan", kondisiKesehatan);
                                    editor.apply();
                                    // Log.d("Kesehatan", "Menyimpan kondisi: " + kondisiKesehatan);
                                    // Log.d("LOGIN_ID_SANTRI", "ID Santri disimpan ke SharedPreferences: " + idSantri);

                                    Toast.makeText(MainActivity.this, "Login berhasil!", Toast.LENGTH_SHORT).show();

                                    FirebaseMessaging.getInstance().getToken().addOnCompleteListener(task -> {
                                        if (task.isSuccessful()) {
                                            String fcmToken = task.getResult();
                                            // Log.d("FCM_TOKEN", "Token didapatkan: " + fcmToken);

                                            saveTokenToServer(idWaliSantri, fcmToken, () -> {
                                                // Callback setelah token tersimpan, lanjut ke HomeActivity
                                                Intent intent = new Intent(MainActivity.this, HomeActivity.class);
                                                intent.putExtra("id_santri", idSantri);
                                                intent.putExtra("id_wali_santri", idWaliSantri);

                                                String loginKey = inputEmailOrNIS.contains("@") ? "email" : "NIS";
                                                intent.putExtra("login_key", loginKey);
                                                intent.putExtra("login_value", inputEmailOrNIS);

                                                startActivity(intent);
                                                finish();
                                            });
                                        } else {
                                            // Log.e("FCM_TOKEN_ERR", "Gagal mendapatkan token FCM: " + task.getException());
                                        }
                                    });

                                    Intent intent = new Intent(MainActivity.this, HomeActivity.class);
                                    intent.putExtra("id_santri", idSantri);
                                    intent.putExtra("id_wali_santri", idWaliSantri);

                                    String loginKey = inputEmailOrNIS.contains("@") ? "email" : "NIS";
                                    intent.putExtra("login_key", loginKey);
                                    intent.putExtra("login_value", inputEmailOrNIS);

                                    startActivity(intent);
                                    finish();

                                } catch (JSONException e) {
                                    e.printStackTrace();
                                    Toast.makeText(MainActivity.this, "Gagal parsing data!", Toast.LENGTH_SHORT).show();
                                }
                            } else {
                                Toast.makeText(MainActivity.this, "Login gagal! Email/NIS atau password salah.", Toast.LENGTH_SHORT).show();
                            }
                        });

                    } else {
                        runOnUiThread(() ->
                                Toast.makeText(MainActivity.this, "Gagal terhubung ke server.", Toast.LENGTH_SHORT).show()
                        );
                    }
                    conn.disconnect();

                } catch (Exception e) {
                    e.printStackTrace();
                    runOnUiThread(() ->
                            Toast.makeText(MainActivity.this, "Terjadi kesalahan: " + e.getMessage(), Toast.LENGTH_SHORT).show()
                    );
                }
            }).start();
        });

    }
    private void saveTokenToServer(String idWaliSantri, String token, Runnable onSuccess) {
        String url = ApiHelper.getBaseUrl() + "saveToken";

        JSONObject jsonBody = new JSONObject();
        try {
            jsonBody.put("id_wali_santri", idWaliSantri);
            jsonBody.put("token", token);
        } catch (JSONException e) {
            e.printStackTrace();
            return;
        }

        JsonObjectRequest request = new JsonObjectRequest(
                Request.Method.POST, url, jsonBody,
                response -> {
                    Log.d("FCM_TOKEN", "Token berhasil dikirim: " + token);
                    if (onSuccess != null) {
                        onSuccess.run(); // jalankan callback jika tidak null
                    }
                },
                error -> Log.e("FCM_TOKEN_ERR", "Gagal kirim token: " + error.toString())
        );

        Volley.newRequestQueue(this).add(request);
    }


}
