package com.carmaintenance;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.google.android.material.textfield.TextInputEditText;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class LoginActivity extends AppCompatActivity {
    private TextInputEditText usernameInput;
    private TextInputEditText passwordInput;
    private ProgressBar loginProgress;
    private TextView loginError;

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

        usernameInput = findViewById(R.id.usernameInput);
        passwordInput = findViewById(R.id.passwordInput);
        loginProgress = findViewById(R.id.loginProgress);
        loginError = findViewById(R.id.loginError);
        Button loginButton = findViewById(R.id.loginButton);

        loginButton.setOnClickListener(v -> attemptLogin());
    }

    private void attemptLogin() {
        String username = textOf(usernameInput);
        String password = textOf(passwordInput);

        if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password)) {
            showError("Username and password are required.");
            return;
        }

        setLoading(true);
        LoginRequest request = new LoginRequest(username, password);

        ApiClient.getService().login(request).enqueue(new Callback<ApiResult<LoginResponse>>() {
            @Override
            public void onResponse(Call<ApiResult<LoginResponse>> call, Response<ApiResult<LoginResponse>> response) {
                setLoading(false);

                if (!response.isSuccessful() || response.body() == null) {
                    showError("Login failed. Please try again.");
                    return;
                }

                ApiResult<LoginResponse> result = response.body();
                if (result.getCode() != 200 || result.getData() == null) {
                    showError(result.getMessage() != null ? result.getMessage() : "Login failed.");
                    return;
                }

                LoginResponse data = result.getData();
                new TokenStore(LoginActivity.this).saveToken(data.getToken());

                String role = data.getUserInfo() != null ? data.getUserInfo().getRole() : "unknown";
                String displayName = data.getUserInfo() != null ? data.getUserInfo().getUsername() : username;

                Intent intent = new Intent(LoginActivity.this, RoleHomeActivity.class);
                intent.putExtra("role", role);
                intent.putExtra("username", displayName);
                startActivity(intent);
                finish();
            }

            @Override
            public void onFailure(Call<ApiResult<LoginResponse>> call, Throwable t) {
                setLoading(false);
                showError("Network error: " + t.getMessage());
            }
        });
    }

    private String textOf(TextInputEditText input) {
        if (input.getText() == null) {
            return "";
        }
        return input.getText().toString().trim();
    }

    private void setLoading(boolean loading) {
        loginProgress.setVisibility(loading ? View.VISIBLE : View.GONE);
        loginError.setVisibility(View.GONE);
    }

    private void showError(String message) {
        loginError.setText(message);
        loginError.setVisibility(View.VISIBLE);
    }
}
