package com.rainbow.app.keyboard.uiactivity;


import android.content.Context;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;

import androidx.activity.EdgeToEdge;
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 com.ad.tradpluslibrary.TPAdManager;
import com.rainbow.app.keyboard.R;
import com.rainbow.app.keyboard.databinding.ActivityEditvBinding;
import com.rainbow.app.keyboard.utils.UtilsKeyname;
import com.rainbow.app.keyboard.utils.UtilsCommon;
import com.rainbow.app.keyboard.utils.UtilsFastblur;
import com.rainbow.app.keyboard.utils.UtilsSavecurrentkb;


public class EditVActivity extends AppCompatActivity {
    private ActivityEditvBinding vb;
    public static String key_name = "key_name";
    private int mPreviousKeyboardHeight = -1;
    private Drawable blurBackground;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        vb = ActivityEditvBinding.inflate(getLayoutInflater());
        EdgeToEdge.enable(this);
        setContentView(vb.getRoot());
        TPAdManager.INSTANCE.loadAllAd(this);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        onInit();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 清理资源
        blurBackground = null;
    }

    public void onInit() {
        String stringExtra = getIntent().getStringExtra(key_name);
        vb.title.setText(stringExtra);
        vb.title.setTypeface(vb.title.getTypeface(), Typeface.BOLD);
        String curPath = UtilsSavecurrentkb.INSTANCE.getSkinPath();

        vb.idBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        if (curPath == null) {
            return;
        }

        String bgPath = curPath + "res/drawable-xxhdpi-v4/" + UtilsKeyname.previewBg;

        Drawable bgDraw = UtilsCommon.INSTANCE.getBgDrawable(this, bgPath);
        if (bgDraw != null) {
            // 使用FastBlur进行模糊处理
            applyBlurBackground(bgDraw);
        }

        keyboardheight();
        setupEditText();
        vb.et.requestFocus();

        // 针对不同 API 设置不同的软键盘模式
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            // API 30+
            getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        } else {
            getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        }

        // 延迟显示键盘
        showKeyboardWithDelay();
    }
    private void setupEditText() {
        // 设置焦点监听
        vb.et.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    showKeyboard();
                }
            }
        });

        // 设置点击监听
        vb.et.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showKeyboard();
            }
        });
    }

    private void showKeyboard() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.showSoftInput(vb.et, InputMethodManager.SHOW_IMPLICIT);
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (!isKeyboardVisible()) {
                        // 方法2：尝试强制显示
                        imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
                    }
                }
            }, 200);
        }
    }

    private void showKeyboardWithDelay() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (!isKeyboardVisible()) {
                    showKeyboard();
                }
            }
        }, 300);
    }

    private boolean isKeyboardVisible() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        return imm != null && imm.isActive(vb.et);
    }
    private void applyBlurBackground(Drawable originalDrawable) {
        // 在子线程中进行模糊处理，避免阻塞UI
        new Thread(() -> {
            try {
                // 使用FastBlur进行模糊
                Drawable blurredDrawable = UtilsFastblur.blurDrawable(originalDrawable, 15, this);

                runOnUiThread(() -> {
                    if (blurredDrawable != null) {
                        blurBackground = blurredDrawable;
                        vb.main.setBackground(blurredDrawable);
                    } else {
                        // 如果模糊失败，使用原始背景
                        vb.main.setBackground(originalDrawable);
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
                runOnUiThread(() -> {
                    // 异常情况下使用原始背景
                    vb.main.setBackground(originalDrawable);
                });
            }
        }).start();
    }

    private void keyboardheight() {
        final View rootView = getWindow().getDecorView();
        rootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                Rect r = new Rect();
                rootView.getWindowVisibleDisplayFrame(r);
                int screenHeight = rootView.getRootView().getHeight();
                int keypadHeight = screenHeight - r.bottom;

                if (keypadHeight != mPreviousKeyboardHeight) {
                    if (mPreviousKeyboardHeight < keypadHeight) {
                        mPreviousKeyboardHeight = keypadHeight;
                        ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) vb.et.getLayoutParams();
                        params.bottomMargin = mPreviousKeyboardHeight;
                        vb.et.setLayoutParams(params);
                    }

                }
            }
        });
    }
}