package tr.dhee.abox.demo.ui.login;

import androidx.activity.EdgeToEdge;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import android.content.Context;
import android.content.SharedPreferences;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import tr.dhee.abox.demo.R;
import tr.dhee.abox.demo.ui.switchcontrol.SwitchControlActivity;
import tr.dhee.abox.demo.databinding.ActivityLoginBinding;
import tr.dhee.abox.demo.utils.AboxConstants;

public class LoginActivity extends AppCompatActivity {

    private LoginViewModel loginViewModel;
    private ActivityLoginBinding binding;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);

        binding = ActivityLoginBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        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;
        });
        loginViewModel = new ViewModelProvider(this, new LoginViewModelFactory())
                .get(LoginViewModel.class);

        final EditText usernameEditText = binding.username;
        final EditText passwordEditText = binding.password;
        final CheckBox checkBoxAutoLogin = binding.checkBoxAutoLogin;
        final Button loginButton = binding.login;
        final ProgressBar loadingProgressBar = binding.loading;

        // 自动登录: 读取上次保存的凭据填充, 若勾选过"记住密码"则直接发起登录
        SharedPreferences sp = getSharedPreferences(AboxConstants.AUTOLOGINFILE, Context.MODE_PRIVATE);
        boolean autoFlag = sp.getBoolean(AboxConstants.AutoLoginClass.AUTOLOGIN_FLAG, false);
        String savedUser = sp.getString(AboxConstants.AutoLoginClass.AUTOLOGIN_USERNAME, "");
        String savedPwd = sp.getString(AboxConstants.AutoLoginClass.AUTOLOGIN_USERPWD, "");
        if (!savedUser.isEmpty()) {
            usernameEditText.setText(savedUser);
            passwordEditText.setText(savedPwd);
            checkBoxAutoLogin.setChecked(autoFlag);
            // 显式触发表单校验, 确保预填充凭据后登录按钮可用
            loginViewModel.loginDataChanged(savedUser, savedPwd);
            if (autoFlag && !savedPwd.isEmpty()) {
                // 延迟一帧, 等观察者注册完再自动登录
                usernameEditText.post(() -> loginViewModel.login(savedUser, savedPwd));
            }
        }

        loginViewModel.getLoginFormState().observe(this, new Observer<LoginFormState>() {
            @Override
            public void onChanged(@Nullable LoginFormState loginFormState) {
                if (loginFormState == null) {
                    return;
                }
                loginButton.setEnabled(loginFormState.isDataValid());
                if (loginFormState.getUsernameError() != null) {
                    usernameEditText.setError(getString(loginFormState.getUsernameError()));
                }
                if (loginFormState.getPasswordError() != null) {
                    passwordEditText.setError(getString(loginFormState.getPasswordError()));
                }
            }
        });

        loginViewModel.getLoginResult().observe(this, new Observer<LoginResult>() {
            @Override
            public void onChanged(@Nullable LoginResult loginResult) {
                if (loginResult == null) {
                    return;
                }
                loadingProgressBar.setVisibility(View.GONE);
                if (loginResult.getError() != null) {
                    showLoginFailed(loginResult.getError());
                }
                if (loginResult.getSuccess() != null) {
                    // 登录成功: 按勾选状态保存凭据到 SharedPreferences(与 base 行为一致)
                    String user = usernameEditText.getText().toString();
                    String pwd = passwordEditText.getText().toString();
                    boolean remember = checkBoxAutoLogin.isChecked();
                    SharedPreferences sp = getSharedPreferences(AboxConstants.AUTOLOGINFILE, Context.MODE_PRIVATE);
                    sp.edit().putString(AboxConstants.AutoLoginClass.AUTOLOGIN_USERNAME, user)
                            .putString(AboxConstants.AutoLoginClass.AUTOLOGIN_USERPWD, pwd)
                            .putBoolean(AboxConstants.AutoLoginClass.AUTOLOGIN_FLAG, remember)
                            .apply();
                    updateUiWithUser(loginResult.getSuccess());
                    // 跳转到插座控制页面
                    Intent intent = new Intent(LoginActivity.this, SwitchControlActivity.class);
                    startActivity(intent);
                    finish();
                }
            }
        });

        TextWatcher afterTextChangedListener = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // ignore
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // ignore
            }

            @Override
            public void afterTextChanged(Editable s) {
                loginViewModel.loginDataChanged(usernameEditText.getText().toString(),
                        passwordEditText.getText().toString());
            }
        };
        usernameEditText.addTextChangedListener(afterTextChangedListener);
        passwordEditText.addTextChangedListener(afterTextChangedListener);
        passwordEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    loginViewModel.login(usernameEditText.getText().toString(),
                            passwordEditText.getText().toString());
                }
                return false;
            }
        });

        loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loadingProgressBar.setVisibility(View.VISIBLE);
                loginViewModel.login(usernameEditText.getText().toString(),
                        passwordEditText.getText().toString());
            }
        });
    }

    private void updateUiWithUser(LoggedInUserView model) {
        String welcome = getString(R.string.welcome) + model.getDisplayName();
        Toast.makeText(getApplicationContext(), welcome, Toast.LENGTH_LONG).show();
    }

    private void showLoginFailed(String errorString) {
        Toast.makeText(getApplicationContext(), errorString, Toast.LENGTH_SHORT).show();
    }
}
