package com.miraclegarden.smsmessage.Activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.miraclegarden.library.app.MiracleGardenActivity;
import com.miraclegarden.smsmessage.databinding.ActivityLoginBinding;
import com.miraclegarden.smsmessage.model.ApiError;
import com.miraclegarden.smsmessage.model.LoginResponse;
import com.miraclegarden.smsmessage.network.ApiService;
import com.miraclegarden.smsmessage.network.TokenManager;

/**
 * 登录页面
 */
public class LoginActivity extends MiracleGardenActivity<ActivityLoginBinding> {

    private ApiService apiService;
    private TokenManager tokenManager;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        apiService = new ApiService(this);
        tokenManager = TokenManager.getInstance(this);

        if (tokenManager.isLoggedIn()) {
            navigateToMain();
            return;
        }

        initView();
    }

    private void initView() {
        binding.btnLogin.setOnClickListener(v -> attemptLogin());
    }

    private void attemptLogin() {
        String username = binding.etUsername.getText().toString().trim();
        String password = binding.etPassword.getText().toString().trim();

        if (TextUtils.isEmpty(username)) {
            binding.etUsername.setError("请输入用户名");
            binding.etUsername.requestFocus();
            return;
        }

        if (TextUtils.isEmpty(password)) {
            binding.etPassword.setError("请输入密码");
            binding.etPassword.requestFocus();
            return;
        }

        showLoading(true);

        apiService.login(username, password, new ApiService.ApiCallback<LoginResponse>() {
            @Override
            public void onSuccess(LoginResponse result) {
                runOnUiThread(() -> {
                    showLoading(false);
                    tokenManager.saveLoginData(result);

                    if (result.isFirstLogin()) {
                        navigateToChangePassword();
                    } else {
                        Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
                        navigateToMain();
                    }
                });
            }

            @Override
            public void onError(ApiError error) {
                runOnUiThread(() -> {
                    showLoading(false);
                    String msg;
                    switch (error.getStatusCode()) {
                        case 400:
                            msg = "用户名和密码不能为空";
                            break;
                        case 401:
                            msg = "用户名或密码错误";
                            break;
                        case 403:
                            msg = "账户已被停用，请联系管理员";
                            break;
                        default:
                            msg = "登录失败: " + error.getMessage();
                    }
                    Toast.makeText(LoginActivity.this, msg, Toast.LENGTH_LONG).show();
                });
            }
        });
    }

    private void showLoading(boolean show) {
        binding.progressBar.setVisibility(show ? View.VISIBLE : View.GONE);
        binding.btnLogin.setEnabled(!show);
    }

    private void navigateToMain() {
        Intent intent = new Intent(this, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
        finish();
    }

    private void navigateToChangePassword() {
        Intent intent = new Intent(this, ChangePasswordActivity.class);
        startActivity(intent);
        finish();
    }
}
