package com.example.petstoremobile.activities;

import android.content.Intent;
import android.os.Bundle;
import android.view.inputmethod.EditorInfo;
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 androidx.lifecycle.ViewModelProvider;

import com.example.petstoremobile.api.auth.TokenManager;
import com.example.petstoremobile.databinding.ActivityMainBinding;
import com.example.petstoremobile.viewmodels.AuthViewModel;
import com.example.petstoremobile.utils.Resource;
import com.example.petstoremobile.utils.UIUtils;

import javax.inject.Inject;
import javax.inject.Named;

import dagger.hilt.android.AndroidEntryPoint;

//The login screen activity
@AndroidEntryPoint
public class MainActivity extends AppCompatActivity {

    private ActivityMainBinding binding;
    private AuthViewModel viewModel;

    @Inject TokenManager tokenManager;
    @Inject @Named("baseUrl") String baseUrl;

    /**
     * Initializes the activity, sets up the UI, and checks for an existing login session.
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        EdgeToEdge.enable(this);
        super.onCreate(savedInstanceState);

        // Check if user is already logged in
        if (tokenManager.isLoggedIn()) {
            if ("CUSTOMER".equalsIgnoreCase(tokenManager.getRole())) {
                // If a customer somehow remained logged in, clear them out
                tokenManager.clearLoginData();
            } else {
                startActivity(new Intent(this, HomeActivity.class));
                finish();
                return;
            }
        }

        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        viewModel = new ViewModelProvider(this).get(AuthViewModel.class);

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

        //clear login status
        binding.tvLoginStatus.setText("");

        // Set editor action listener for password field to login on when enter is pressed
        binding.etPassword.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_DONE || actionId == EditorInfo.IME_NULL) {
                binding.btnLogin.performClick();
                return true;
            }
            return false;
        });

        //Set click listener for login button
        binding.btnLogin.setOnClickListener(v -> {
            //Get username and password from text fields
            String username = binding.etUser.getText().toString();
            String password = binding.etPassword.getText().toString();

            //check if fields are empty
            if (username.isEmpty() || password.isEmpty()) {
                Toast.makeText(this, "Please enter username and password", Toast.LENGTH_SHORT).show();
                binding.tvLoginStatus.setText("Please enter username and password");
                return;
            }

            performLogin(username, password);
        });

        // Set click listener for forgot password link
        binding.tvForgotPassword.setOnClickListener(v -> {
            startActivity(new Intent(this, ForgotPasswordActivity.class));
        });
    }

    /**
     * Executes the login process using the AuthViewModel and handles the authentication response.
     */
    private void performLogin(String username, String password) {
        viewModel.login(username, password).observe(this, resource -> {
            if (resource == null) return;

            switch (resource.status) {
                case LOADING:
                    UIUtils.setViewsEnabled(false, binding.btnLogin);
                    binding.tvLoginStatus.setText("Logging in...");
                    break;
                case SUCCESS:
                    if (resource.data != null) {
                        String role = resource.data.getRole();
                        if ("CUSTOMER".equalsIgnoreCase(role)) {
                            UIUtils.setViewsEnabled(true, binding.btnLogin);
                            binding.tvLoginStatus.setText("Customers are not allowed to log in");
                            Toast.makeText(this, "Access denied: Customers are not allowed to log in.", Toast.LENGTH_LONG).show();
                        } else {
                            tokenManager.saveLoginData(resource.data.getToken(), resource.data.getUsername(), role);
                            fetchUserIdAndNavigate();
                        }
                    }
                    break;
                case ERROR:
                    UIUtils.setViewsEnabled(true, binding.btnLogin);
                    binding.tvLoginStatus.setText(resource.message);
                    Toast.makeText(this, resource.message, Toast.LENGTH_LONG).show();
                    break;
            }
        });
    }

    /**
     * Retrieves the logged-in user's profile information to save their ID before navigating to the home screen.
     */
    private void fetchUserIdAndNavigate() {
        viewModel.getMe().observe(this, resource -> {
            if (resource != null && resource.status != Resource.Status.LOADING) {
                if (resource.status == Resource.Status.SUCCESS && resource.data != null) {
                    tokenManager.saveUserId(resource.data.getId());
                    tokenManager.savePrimaryStoreId(resource.data.getStoreId());
                }
                Toast.makeText(this, "Login successful", Toast.LENGTH_SHORT).show();
                startActivity(new Intent(this, HomeActivity.class));
                finish();
            }
        });
    }
}
