package com.videogo.ui.others;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import androidx.appcompat.app.AlertDialog;

import com.videogo.util.Utils;
import com.videogo.widget.IOSAlertDialog;

import com.videogo.global.ValueKeys;
import com.videogo.ui.LanDevice.LanDeviceActivity;
import com.videogo.util.DataManager;
import com.videogo.util.SpTool;
import com.videogo.widget.TitleBar;
import com.videogo.widget.testlist.TestItem;
import com.videogo.widget.testlist.TestItemAdapter;

import java.util.ArrayList;
import java.util.List;

import ezviz.ezopensdkcommon.common.RootActivity;
import ezviz.ezopensdk.R;

/**
 * 萤石功能测试页面
 * 通过配置数组来展示功能列表
 */
public class EZTestActivity extends RootActivity {

    // 特殊功能标识常量
    private static final String SPECIAL_AUTO_TEST = "SPECIAL_AUTO_TEST";
    private static final String SPECIAL_SPACE_ID = "SPECIAL_SPACE_ID";
    private static final String SPECIAL_CLEAR_VERIFY_CODE = "SPECIAL_CLEAR_VERIFY_CODE";

    private ListView listView;
    private TitleBar titleBar;
    private List<TestItem> testItems;
    private TestItemAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ez_test);
        
        initViews();
        setupDataArray();
        setupListView();
    }
    
    /**
     * 初始化视图
     */
    private void initViews() {
        titleBar = findViewById(R.id.title_bar);
        titleBar.setTitle("萤石功能测试");
        titleBar.addBackButton(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        
        listView = findViewById(R.id.list_view);
    }
    
    /**
     * 配置功能数组 - 参考iOS的array配置方式
     */
    private void setupDataArray() {
        testItems = new ArrayList<>();
        
        // 根据自动化测试状态显示不同标题
        String autoTestTitle = SpTool.obtainBooleanValue(ValueKeys.AUTO_TEST) 
            ? "自动化测试(开启)" : "自动化测试(关闭)";
        
        // 配置功能列表 - 格式: [标题, Activity类名或特殊功能标识]
        // Activity类名: 跳转到对应Activity
        // SPECIAL_开头: 特殊功能处理
        testItems.add(new TestItem("设备发现", "LanDeviceActivity"));
        testItems.add(new TestItem("P2P测试", "EZP2pTestActivity"));
        testItems.add(new TestItem(autoTestTitle, SPECIAL_AUTO_TEST));
        testItems.add(new TestItem("取流方式设置", "EZStreamTypeSettingActivity"));
        testItems.add(new TestItem("取流特殊设置", "EZStreamConfigSettingActivity"));
        testItems.add(new TestItem("设置云录制SpaceId", SPECIAL_SPACE_ID));
        testItems.add(new TestItem("小权限tkToken设置", "EZTKTokenActivity"));
        testItems.add(new TestItem("接口测试", "EZInterfaceTestActivity"));
        testItems.add(new TestItem("设备验证码清空", SPECIAL_CLEAR_VERIFY_CODE));
    }
    
    /**
     * 设置ListView
     */
    private void setupListView() {
        // 使用TestItemAdapter来显示主标题和副标题(类似iOS的UITableViewCellStyleSubtitle)
        adapter = new TestItemAdapter(this, testItems);
        listView.setAdapter(adapter);
        
        // 设置点击事件
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                handleItemClick(position);
            }
        });
    }
    
    /**
     * 处理列表项点击事件
     */
    private void handleItemClick(int position) {
        TestItem item = testItems.get(position);
        
        if (item.isActivityItem()) {
            // 跳转到对应的Activity
            navigateToActivity(item.getClassName(), item.getTitle());
        } else if (item.isSpecialItem()) {
            // 特殊功能处理
            handleSpecialItem(item.getClassName());
        }
    }
    
    /**
     * 跳转到指定Activity
     */
    private void navigateToActivity(String className, String title) {
        try {
            Class<?> targetClass = null;
            
            // 根据类名获取对应的Class
            switch (className) {
                case "LanDeviceActivity":
                    targetClass = LanDeviceActivity.class;
                    break;
                case "EZP2pTestActivity":
                    targetClass = EZP2pTestActivity.class;
                    break;
                case "EZStreamTypeSettingActivity":
                    targetClass = EZStreamTypeSettingActivity.class;
                    break;
                case "EZStreamConfigSettingActivity":
                    targetClass = EZStreamConfigSettingActivity.class;
                    break;
                case "EZTKTokenActivity":
                    targetClass = EZTKTokenActivity.class;
                    break;
                case "EZInterfaceTestActivity":
                    targetClass = EZInterfaceTestActivity.class;
                    break;
            }
            
            if (targetClass != null) {
                Intent intent = new Intent(this, targetClass);
                startActivity(intent);
            }
        } catch (Exception e) {
            e.printStackTrace();
            showToast("页面跳转失败: " + e.getMessage());
        }
    }
    
    /**
     * 处理特殊功能项 - 根据特殊标识符处理
     */
    private void handleSpecialItem(String specialType) {
        switch (specialType) {
            case SPECIAL_AUTO_TEST: // 自动化测试
                showAutoTestDialog();
                break;
            case SPECIAL_SPACE_ID: // 设置云录制SpaceId
                showSpaceIdDialog();
                break;
            case SPECIAL_CLEAR_VERIFY_CODE: // 设备验证码清空
                showClearVerifyCodeDialog();
                break;
        }
    }
    
    /**
     * 显示自动化测试对话框
     */
    private void showAutoTestDialog() {
        new AlertDialog.Builder(this)
            .setTitle("是否开启自动化测试")
            .setMessage("萤石SDK测试人员专用,开启后本应用中的账号登录和退出功能将禁用")
            .setPositiveButton("确定", (dialog, which) -> {
                SpTool.storeBooleanValue(ValueKeys.AUTO_TEST, true);
                // 刷新列表显示
                setupDataArray();
                adapter.updateData(testItems);
            })
            .setNegativeButton("取消", null)
            .create()
            .show();
    }
    
    /**
     * 显示SpaceId设置对话框（参照EZTKTokenActivity的设备级tkToken设置弹框样式）
     */
    private void showSpaceIdDialog() {
        final Dialog dialog = new Dialog(this, R.style.IOSAlertDialogStyle);
        dialog.setContentView(R.layout.dialog_ios_multi_input);
        dialog.setCanceledOnTouchOutside(true);

        Window window = dialog.getWindow();
        if (window != null) {
            window.setGravity(Gravity.CENTER);
            WindowManager.LayoutParams lp = window.getAttributes();
            lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
            lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
            window.setAttributes(lp);
            window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE
                    | WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
        }

        TextView titleTv = dialog.findViewById(R.id.tv_ios_dialog_title);
        LinearLayout inputContainer = dialog.findViewById(R.id.ll_ios_dialog_input_container);
        TextView negativeBtn = dialog.findViewById(R.id.btn_ios_dialog_negative);
        TextView positiveBtn = dialog.findViewById(R.id.btn_ios_dialog_positive);

        titleTv.setText(getString(R.string.space_id_dialog_title));

        // 创建输入框
        final EditText spaceIdEdit = createInputField(inputContainer,
                getString(R.string.space_id_input_hint), InputType.TYPE_CLASS_TEXT);

        negativeBtn.setOnClickListener(v -> dialog.dismiss());
        positiveBtn.setOnClickListener(v -> {
            String spaceId = spaceIdEdit.getText().toString();
            if (TextUtils.isEmpty(spaceId)) {
                showToast(getString(R.string.space_id_empty_tip));
                return;
            }
            dialog.dismiss();
            SpTool.storeValue(ValueKeys.SDK_CLOUD_SPACEID, spaceId);
            showToast(getString(R.string.space_id_set_success));
        });

        dialog.show();
    }

    /**
     * 创建iOS风格输入框（参照EZTKTokenActivity.createInputField）
     */
    private EditText createInputField(LinearLayout container, String hint, int inputType) {
        EditText editText = new EditText(this);
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT, Utils.dip2px(this, 36));
        editText.setLayoutParams(lp);
        editText.setTextSize(14);
        editText.setTextColor(0xFF000000);
        editText.setHintTextColor(0xFF999999);
        editText.setSingleLine(true);
        editText.setInputType(inputType);
        editText.setHint(hint);
        editText.setPadding(Utils.dip2px(this, 12), 0, Utils.dip2px(this, 12), 0);
        // 单个输入框：四角都圆
        editText.setBackgroundResource(R.drawable.bg_ios_dialog_input);
        container.addView(editText);
        return editText;
    }
    
    /**
     * 显示清空验证码对话框
     */
    private void showClearVerifyCodeDialog() {
        new IOSAlertDialog.Builder(this)
                .setMessage(R.string.clear_verify_code_tip)
                .setNegativeButton(R.string.cancel, null)
                .setPositiveButton(R.string.certain, v -> {
                    DataManager.getInstance().clearAllDeviceSerialVerifyCode();
                    showToast(getString(R.string.clear_verify_code_success));
                })
                .show();
    }
}
