package com.example.petstoremobile.activities;

import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.example.petstoremobile.api.auth.AuthApi;
import com.example.petstoremobile.databinding.ActivityForgotPasswordBinding;
import com.example.petstoremobile.utils.InputValidator;

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

import javax.inject.Inject;

import dagger.hilt.android.AndroidEntryPoint;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

@AndroidEntryPoint
public class ForgotPasswordActivity extends AppCompatActivity {

    @Inject
    AuthApi authApi;

    private ActivityForgotPasswordBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        EdgeToEdge.enable(this);
        super.onCreate(savedInstanceState);
        binding = ActivityForgotPasswordBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        ViewCompat.setOnApplyWindowInsetsListener(binding.forgotPasswordRoot, (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        binding.btnSubmit.setOnClickListener(v -> {
            if (!InputValidator.isValidEmail(binding.etEmail)) return;
            String email = binding.etEmail.getText().toString().trim();
            sendResetLink(email);
        });

        binding.btnBackToLogin.setOnClickListener(v -> finish());
    }

    private void sendResetLink(String email) {
        binding.btnSubmit.setEnabled(false);

        Map<String, String> body = new HashMap<>();
        body.put("usernameOrEmail", email);

        authApi.forgotPassword(body).enqueue(new Callback<Void>() {
            @Override
            public void onResponse(Call<Void> call, Response<Void> response) {
                if (binding == null) return;
                binding.btnSubmit.setEnabled(true);
                Toast.makeText(ForgotPasswordActivity.this,
                        "If this email is registered, a reset link will be sent.",
                        Toast.LENGTH_LONG).show();
                finish();
            }

            @Override
            public void onFailure(Call<Void> call, Throwable t) {
                if (binding == null) return;
                binding.btnSubmit.setEnabled(true);
                Toast.makeText(ForgotPasswordActivity.this,
                        "Could not send reset link. Please try again.",
                        Toast.LENGTH_LONG).show();
            }
        });
    }
}
