package com.ttstd.controlled.activity.settings;

import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;

import com.ttstd.controlled.R;
import com.ttstd.controlled.base.BaseMvvmActivity;
import com.ttstd.controlled.databinding.ActivitySettingsBinding;
import com.ttstd.controlled.utils.AuthSettings;
import com.ttstd.controlled.utils.InputSettings;

/**
 * 安全与输入设置页：
 * - 动态验证码（显示 / 重新生成）
 * - 固定密码（设置并确认）
 * - 允许免密连接开关
 * - 模拟点击方式（自动 / 系统注入 / Root / 无障碍 / 普通 Shell）
 */
public class SettingsActivity extends BaseMvvmActivity<SettingsViewModel, ActivitySettingsBinding> {

    /** Spinner 选项与 InputSettings 常量的一一对应（顺序须与 string-array 一致）。 */
    private static final String[] METHOD_BY_POSITION = {
            InputSettings.METHOD_AUTO,
            InputSettings.METHOD_SYSTEM,
            InputSettings.METHOD_ROOT,
            InputSettings.METHOD_ACCESSIBILITY,
            InputSettings.METHOD_SHELL
    };

    @Override
    protected int getLayoutId() {
        return R.layout.activity_settings;
    }

    @Override
    protected void initView() {
        setupInputMethodSpinner();
        setupAuth();
    }

    /** 构建并初始化「模拟点击方式」下拉框，选中当前已保存的方式。 */
    private void setupInputMethodSpinner() {
        Spinner spinner = binding.spinnerInputMethod;
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
                this, R.array.input_method_entries, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);

        String current = InputSettings.getInputMethod(this);
        int selectIdx = 0;
        for (int i = 0; i < METHOD_BY_POSITION.length; i++) {
            if (METHOD_BY_POSITION[i].equals(current)) {
                selectIdx = i;
                break;
            }
        }
        spinner.setSelection(selectIdx);
        updateInputMethodHint(METHOD_BY_POSITION[selectIdx]);

        spinner.setOnItemSelectedListener(new android.widget.AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(android.widget.AdapterView<?> parent, android.view.View view,
                                       int position, long id) {
                String method = METHOD_BY_POSITION[position];
                InputSettings.setInputMethod(SettingsActivity.this, method);
                updateInputMethodHint(method);
                binding.tvInputMethodHint.setText(R.string.input_method_saved);
            }

            @Override
            public void onNothingSelected(android.widget.AdapterView<?> parent) {
            }
        });
    }

    /** 根据选中的方式展示说明（仅展示，不覆盖已保存状态）。 */
    private void updateInputMethodHint(String method) {
        int resId;
        switch (method) {
            case InputSettings.METHOD_SYSTEM:
                resId = R.string.input_method_system;
                break;
            case InputSettings.METHOD_ROOT:
                resId = R.string.input_method_root;
                break;
            case InputSettings.METHOD_ACCESSIBILITY:
                resId = R.string.input_method_accessibility;
                break;
            case InputSettings.METHOD_SHELL:
                resId = R.string.input_method_shell;
                break;
            case InputSettings.METHOD_AUTO:
            default:
                resId = R.string.input_method_auto;
                break;
        }
        binding.tvInputMethodHint.setText(getString(R.string.input_method_desc) + "\n" + getString(resId));
    }

    /** 动态验证码、固定密码与免密连接开关。 */
    private void setupAuth() {
        binding.tvDynamicCode.setText(AuthSettings.getDynamicCode(this));
        binding.btnRegenerateCode.setOnClickListener(v -> {
            String newCode = AuthSettings.generateDynamicCode();
            AuthSettings.setDynamicCode(this, newCode);
            binding.tvDynamicCode.setText(newCode);
            binding.tvAuthHint.setText("动态验证码已重新生成");
        });
        binding.btnSavePassword.setOnClickListener(v -> {
            String p1 = binding.etFixedPassword.getText().toString();
            String p2 = binding.etConfirmPassword.getText().toString();
            if (p1.isEmpty()) {
                binding.tvAuthHint.setText("固定密码不能为空");
                return;
            }
            if (!p1.equals(p2)) {
                binding.tvAuthHint.setText("两次输入的密码不一致");
                return;
            }
            AuthSettings.setFixedPassword(this, p1);
            binding.etFixedPassword.setText("");
            binding.etConfirmPassword.setText("");
            binding.tvAuthHint.setText("固定密码已保存");
        });

        binding.switchAllowNoAuth.setChecked(AuthSettings.isNoAuthAllowed(this));
        binding.switchAllowNoAuth.setOnCheckedChangeListener((buttonView, isChecked) -> {
            AuthSettings.setNoAuthAllowed(this, isChecked);
            binding.tvAuthHint.setText(isChecked ? R.string.allow_no_auth_on : R.string.allow_no_auth_off);
        });
    }

    @Override
    protected void initData() {
        // 无需额外数据初始化
    }

    @Override
    public void onBackPressed() {
        // 设置即时生效（已写入 SharedPreferences），直接返回主页面。
        Toast.makeText(this, "设置已保存", Toast.LENGTH_SHORT).show();
        super.onBackPressed();
    }
}
