package com.miraclegarden.smsmessage;

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

import com.miraclegarden.smsmessage.databinding.DialogActionConfirmBinding;
import com.miraclegarden.smsmessage.model.ApiError;
import com.miraclegarden.smsmessage.model.BankInfo;
import com.miraclegarden.smsmessage.network.ApiService;
import com.miraclegarden.smsmessage.network.TokenManager;

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

/**
 * 选择银行账户弹窗（添加监听时使用）
 */
public class ActionConfirmDialog extends Dialog {
    private final Context context;
    OnToActionListener onToActionListener;
    AppInfo appInfo;
    int index;
    DialogActionConfirmBinding actionConfirmBinding;
    ApiService apiService;
    TokenManager tokenManager;
    List<BankInfo> bankList = new ArrayList<>();
    BankInfo selectedBank = null;
    private boolean localMode = false;

    public interface OnToActionListener {
        void toSumbit(AppInfo appInfo);
        void toCancel();
    }

    public void setOnToActionListener(OnToActionListener onNextCallListener) {
        this.onToActionListener = onNextCallListener;
    }

    public ActionConfirmDialog(Context context, AppInfo appInfo) {
        super(context, R.style.MaterialDesignDialog);
        this.context = context;
        this.appInfo = appInfo;
        this.apiService = new ApiService(context);
        this.tokenManager = TokenManager.getInstance(context);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        actionConfirmBinding = DialogActionConfirmBinding.inflate(getLayoutInflater());
        setContentView(actionConfirmBinding.getRoot());

        actionConfirmBinding.ivIcon.setImageDrawable(appInfo.getIcon());
        actionConfirmBinding.tvAppname.setText(appInfo.getAppName());
        actionConfirmBinding.tvPackage.setText(appInfo.getPackageName());

        // 未登录时走本地模式，不请求服务器银行账户
        if (!tokenManager.isLoggedIn()) {
            setupLocalMode();
        } else {
            loadBankList();
        }

        actionConfirmBinding.sumbitTv.setOnClickListener(view -> {
            if (localMode) {
                submitLocalMode();
                return;
            }

            if (selectedBank == null) {
                Toast.makeText(context, "请选择关联的银行账户", Toast.LENGTH_SHORT).show();
                return;
            }

            appInfo.setBankInfoId(selectedBank.getId());
            appInfo.setName(selectedBank.getBankName());
            appInfo.setCode(selectedBank.getAccount());
            if (selectedBank.getRemark() != null) {
                appInfo.setRemark(selectedBank.getRemark());
            }

            if (onToActionListener != null) {
                dismiss();
                onToActionListener.toSumbit(appInfo);
            }
        });

        actionConfirmBinding.cancelTv.setOnClickListener(view -> {
            dismiss();
            if (onToActionListener != null) {
                onToActionListener.toCancel();
            }
        });

        Window window = getWindow();
        WindowManager.LayoutParams wlp = window.getAttributes();
        wlp.gravity = Gravity.CENTER;
        wlp.width = WindowManager.LayoutParams.WRAP_CONTENT;
        wlp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        window.setAttributes(wlp);
    }

    private void loadBankList() {
        actionConfirmBinding.spinnerBank.setEnabled(false);

        apiService.getBankList(new ApiService.ApiCallback<List<BankInfo>>() {
            @Override
            public void onSuccess(List<BankInfo> result) {
                if (context instanceof android.app.Activity) {
                    ((android.app.Activity) context).runOnUiThread(() -> {
                        bankList.clear();
                        if (result != null) {
                            bankList.addAll(result);
                        }

                        if (bankList.isEmpty()) {
                            Toast.makeText(context, "暂无银行账户，请先到银行账户管理添加", Toast.LENGTH_LONG).show();
                            dismiss();
                            return;
                        }

                        setupSpinner();
                    });
                }
            }

            @Override
            public void onError(ApiError error) {
                if (context instanceof android.app.Activity) {
                    ((android.app.Activity) context).runOnUiThread(() -> {
                        Toast.makeText(context, "无法加载银行账户，已切换本地模式", Toast.LENGTH_SHORT).show();
                        setupLocalMode();
                    });
                }
            }
        });
    }

    private void setupLocalMode() {
        localMode = true;
        selectedBank = null;
        actionConfirmBinding.spinnerBank.setVisibility(View.GONE);
        View bankSection = (View) actionConfirmBinding.spinnerBank.getParent();
        if (bankSection != null) {
            for (int i = 0; i < ((android.view.ViewGroup) bankSection).getChildCount(); i++) {
                ((android.view.ViewGroup) bankSection).getChildAt(i).setVisibility(View.GONE);
            }
        }
    }

    private void submitLocalMode() {
        if (TextUtils.isEmpty(appInfo.getBankInfoId())) {
            appInfo.setBankInfoId("local:" + appInfo.getPackageName());
        }
        if (TextUtils.isEmpty(appInfo.getName())) {
            appInfo.setName(appInfo.getAppName());
        }
        if (TextUtils.isEmpty(appInfo.getCode())) {
            appInfo.setCode(appInfo.getPackageName());
        }

        if (onToActionListener != null) {
            dismiss();
            onToActionListener.toSumbit(appInfo);
        }
    }

    private void setupSpinner() {
        List<String> bankNames = new ArrayList<>();
        bankNames.add("请选择银行账户");
        for (BankInfo bank : bankList) {
            bankNames.add(bank.getDisplayName());
        }

        ArrayAdapter<String> adapter = new ArrayAdapter<>(context,
                android.R.layout.simple_spinner_item, bankNames);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        actionConfirmBinding.spinnerBank.setAdapter(adapter);
        actionConfirmBinding.spinnerBank.setEnabled(true);

        actionConfirmBinding.spinnerBank.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (position > 0) {
                    selectedBank = bankList.get(position - 1);
                } else {
                    selectedBank = null;
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                selectedBank = null;
            }
        });

        // 如果已有绑定的银行，选中它
        if (!TextUtils.isEmpty(appInfo.getBankInfoId())) {
            for (int i = 0; i < bankList.size(); i++) {
                if (appInfo.getBankInfoId().equals(bankList.get(i).getId())) {
                    actionConfirmBinding.spinnerBank.setSelection(i + 1);
                    selectedBank = bankList.get(i);
                    break;
                }
            }
        }
    }
}
