package com.videogo.ui.others;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
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 android.widget.Toast;

import com.videogo.global.GlobalKit;
import com.videogo.util.Utils;
import com.videogo.widget.TitleBar;
import com.videogo.widget.testlist.TestItem;
import com.videogo.widget.testlist.TestItemAdapter;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

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

import static com.videogo.EzvizApplication.getOpenSDK;

public class EZTKTokenActivity extends RootActivity {

    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_eztktoken);

        initViews();
        setupDataArray();
        setupListView();
    }

    /**
     * 初始化视图
     */
    private void initViews() {
        titleBar = findViewById(R.id.title_bar);
        titleBar.setTitle("小权限tkToken设置");
        titleBar.addBackButton(view -> finish());

        listView = findViewById(R.id.list_view);
    }

    /**
     * 配置功能数组
     */
    private void setupDataArray() {
        testItems = new ArrayList<>();

        // 格式: [标题, 方法名]
        testItems.add(new TestItem("设备级tkToken设置", "onDeviceTokenSetClick"));
        testItems.add(new TestItem("设备通道级tkToken设置", "onDeviceCameraNoTokenSetClick"));
        testItems.add(new TestItem("预览tkToken设置", "onPreviewTokenSetClick"));
        testItems.add(new TestItem("对讲tkToken设置", "onTalkTokenSetClick"));
        testItems.add(new TestItem("回放tkToken设置", "onPlaybackTokenSetClick"));
    }

    /**
     * 设置ListView
     */
    private void setupListView() {
        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);
        String methodName = item.getClassName();

        try {
            Method method = this.getClass().getDeclaredMethod(methodName);
            method.setAccessible(true);
            method.invoke(this);
        } catch (Exception e) {
            e.printStackTrace();
            showToast("方法调用失败: " + e.getMessage());
        }
    }

    /**
     * 设置设备级token
     */
    private void onDeviceTokenSetClick() {
        TKTokenInputDialog2(this, "设备级tkToken设置", (deviceSerial, tkToken) -> {
            getOpenSDK().setDeviceToken(deviceSerial, tkToken);
        }, "", "").show();
    }

    /**
     * 设置设备通道级token
     */
    private void onDeviceCameraNoTokenSetClick() {
        TKTokenInputDialog4(this, "设备级通道级tkToken设置", (deviceSerial, cameraNo, globalTkToken, videoTkToken) -> {
            getOpenSDK().setDeviceToken(deviceSerial, cameraNo, globalTkToken, videoTkToken);
        }, "", "1", "", "").show();
    }

    /**
     * 设置预览token
     */
    private void onPreviewTokenSetClick() {
        TKTokenInputDialog1(this, "预览tkToken设置", tkToken -> {
            GlobalKit.getInstance().previewStreamToken = tkToken;
        }, "").show();
    }

    /**
     * 设置对讲token
     */
    private void onTalkTokenSetClick() {
        TKTokenInputDialog1(this, "对讲tkToken设置", tkToken -> {
            GlobalKit.getInstance().talkStreamToken = tkToken;
        }, "").show();
    }

    /**
     * 设置回放token
     */
    private void onPlaybackTokenSetClick() {
        TKTokenInputDialog1(this, "回放tkToken设置", tkToken -> {
            GlobalKit.getInstance().playbackStreamToken = tkToken;
        }, "").show();
    }

    // region --- iOS 风格弹框 ---

    /**
     * 创建一个 iOS 风格的输入框并添加到容器中
     * @param position 当前输入框在组中的位置（从0开始）
     * @param total 输入框总数
     */
    private static EditText createInputField(Context context, LinearLayout container, String hint, int inputType, int position, int total) {
        EditText editText = new EditText(context);
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT, Utils.dip2px(context, 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(context, 12), 0, Utils.dip2px(context, 12), 0);

        // 根据位置设置不同圆角背景
        if (total == 1) {
            // 单个输入框：四角都圆
            editText.setBackgroundResource(R.drawable.bg_ios_dialog_input);
        } else if (position == 0) {
            // 第一个：左上右上圆角
            editText.setBackgroundResource(R.drawable.bg_ios_dialog_input_top);
        } else if (position == total - 1) {
            // 最后一个：左下右下圆角
            editText.setBackgroundResource(R.drawable.bg_ios_dialog_input_bottom);
        } else {
            // 中间：无圆角
            editText.setBackgroundResource(R.drawable.bg_ios_dialog_input_middle);
        }

        container.addView(editText);
        return editText;
    }

    /**
     * 一个输入框的Dialog（iOS 风格）
     */
    public static Dialog TKTokenInputDialog1(final Context context, final String title, final tkTokenInputListener1 l, final String... defaults) {
        final Dialog dialog = new Dialog(context, 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(title);

        final EditText tkTokenEdit = createInputField(context, inputContainer, "请输入tkToken", InputType.TYPE_CLASS_TEXT, 0, 1);
        // 预填默认值
        if (defaults.length > 0 && !TextUtils.isEmpty(defaults[0])) {
            tkTokenEdit.setText(defaults[0]);
            tkTokenEdit.setSelection(defaults[0].length());
        }

        negativeBtn.setOnClickListener(v -> dialog.dismiss());
        positiveBtn.setOnClickListener(v -> {
            final String tkToken = tkTokenEdit.getText().toString();
            if (TextUtils.isEmpty(tkToken)) {
                Toast.makeText(context, "The tkToken is empty", Toast.LENGTH_LONG).show();
                return;
            }
            dialog.dismiss();
            l.onInputTKToken(tkToken);
        });

        return dialog;
    }

    public interface tkTokenInputListener1 {

        void onInputTKToken(final String tkToken);
    }

    /**
     * 两个输入框的Dialog（iOS 风格）
     */
    public static Dialog TKTokenInputDialog2(final Context context, final String title, final tkTokenInputListener2 l, final String... defaults) {
        final Dialog dialog = new Dialog(context, 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_HIDDEN);
        }

        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(title);

        final EditText deviceSerialEdit = createInputField(context, inputContainer, "请输入设备序列号", InputType.TYPE_CLASS_TEXT, 0, 2);
        final EditText tkTokenEdit = createInputField(context, inputContainer, "请输入tkToken", InputType.TYPE_CLASS_TEXT, 1, 2);
        // 预填默认值
        if (defaults.length > 0 && !TextUtils.isEmpty(defaults[0])) {
            deviceSerialEdit.setText(defaults[0]);
        }
        if (defaults.length > 1 && !TextUtils.isEmpty(defaults[1])) {
            tkTokenEdit.setText(defaults[1]);
        }

        negativeBtn.setOnClickListener(v -> dialog.dismiss());
        positiveBtn.setOnClickListener(v -> {
            final String deviceSerial = deviceSerialEdit.getText().toString();
            final String tkToken = tkTokenEdit.getText().toString();
            if (TextUtils.isEmpty(deviceSerial)) {
                Toast.makeText(context, "The deviceSerial is empty", Toast.LENGTH_LONG).show();
                return;
            }
            if (TextUtils.isEmpty(tkToken)) {
                Toast.makeText(context, "The tkToken is empty", Toast.LENGTH_LONG).show();
                return;
            }
            dialog.dismiss();
            l.onInputTKToken(deviceSerial, tkToken);
        });

        return dialog;
    }

    public interface tkTokenInputListener2 {

        void onInputTKToken(final String deviceSerial, final String tkToken);
    }

    /**
     * 四个输入框的Dialog（iOS 风格）
     */
    public static Dialog TKTokenInputDialog4(final Context context, final String title, final tkTokenInputListener4 l, final String... defaults) {
        final Dialog dialog = new Dialog(context, 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_HIDDEN);
        }

        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(title);

        final EditText deviceSerialEdit = createInputField(context, inputContainer, "请输入设备序列号", InputType.TYPE_CLASS_TEXT, 0, 4);
        final EditText cameraNoEdit = createInputField(context, inputContainer, "请输入设备通道号，不支持*", InputType.TYPE_CLASS_NUMBER, 1, 4);
        final EditText globalTkTokenEdit = createInputField(context, inputContainer, "请输入global tkToken", InputType.TYPE_CLASS_TEXT, 2, 4);
        final EditText videoTkTokenEdit = createInputField(context, inputContainer, "请输入video tkToken", InputType.TYPE_CLASS_TEXT, 3, 4);
        // 预填默认值
        if (defaults.length > 0 && !TextUtils.isEmpty(defaults[0])) {
            deviceSerialEdit.setText(defaults[0]);
        }
        if (defaults.length > 1 && !TextUtils.isEmpty(defaults[1])) {
            cameraNoEdit.setText(defaults[1]);
        }
        if (defaults.length > 2 && !TextUtils.isEmpty(defaults[2])) {
            globalTkTokenEdit.setText(defaults[2]);
        }
        if (defaults.length > 3 && !TextUtils.isEmpty(defaults[3])) {
            videoTkTokenEdit.setText(defaults[3]);
        }

        negativeBtn.setOnClickListener(v -> dialog.dismiss());
        positiveBtn.setOnClickListener(v -> {
            final String deviceSerial = deviceSerialEdit.getText().toString();
            final String cameraNoString = cameraNoEdit.getText().toString();
            final String globalTKToken = globalTkTokenEdit.getText().toString();
            final String videoTKToken = videoTkTokenEdit.getText().toString();
            if (TextUtils.isEmpty(deviceSerial)) {
                Toast.makeText(context, "The deviceSerial is empty", Toast.LENGTH_LONG).show();
                return;
            }
            if (TextUtils.isEmpty(cameraNoString)) {
                Toast.makeText(context, "The cameraNo is empty", Toast.LENGTH_LONG).show();
                return;
            }
            if (TextUtils.isEmpty(globalTKToken)) {
                Toast.makeText(context, "The global tkToken is empty", Toast.LENGTH_LONG).show();
                return;
            }
            if (TextUtils.isEmpty(videoTKToken)) {
                Toast.makeText(context, "The video tkToken is empty", Toast.LENGTH_LONG).show();
                return;
            }
            dialog.dismiss();
            l.onInputTKToken(deviceSerial, Integer.parseInt(cameraNoString), globalTKToken, videoTKToken);
        });

        return dialog;
    }

    public interface tkTokenInputListener4 {

        void onInputTKToken(final String deviceSerial, final int cameraNo, final String deviceGlobalTKToken, final String deviceVideoTKToken);
    }

    // endregion

}
