package com.app.input.personalised.board.boartactivity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import kotlin.Unit;
import kotlin.jvm.functions.Function0;

import com.ad.tradpluslibrary.TPAdManager;
import com.app.input.personalised.board.BoartApp;
import com.app.input.personalised.board.R;
import com.app.input.personalised.board.databean.KeyboardTheme;
import com.app.input.personalised.board.databean.ThemeCategory;
import com.app.input.personalised.board.databinding.ActivityThemeSearchBinding;
import com.app.input.personalised.board.listhelpers.RecommendedGridAdapter;
import com.app.input.personalised.board.helpers.GridItemDecoration;

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

public class ThemeSearchActivity extends BaseActivity {
    private ActivityThemeSearchBinding vb;
    private RecommendedGridAdapter searchAdapter;
    private List<KeyboardTheme> allItems = new ArrayList<>();
    private List<KeyboardTheme> searchResults = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        vb = ActivityThemeSearchBinding.inflate(getLayoutInflater());
        EdgeToEdge.enable(this);
        setContentView(vb.getRoot());
        com.app.input.personalised.board.helpers.StatusBarHelper.INSTANCE.setTransparentStatusBar(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;
        });

        // 延迟设置状态栏，确保覆盖MaterialComponents主题可能的自动设置
        findViewById(R.id.main).post(() -> {
            com.app.input.personalised.board.helpers.StatusBarHelper.INSTANCE.setTransparentStatusBar(this);
        });

        initData();
        initSearchRecycler();
        initSearchBar();
        initClick();
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 确保状态栏始终为透明
        com.app.input.personalised.board.helpers.StatusBarHelper.INSTANCE.setTransparentStatusBar(this);
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            // 窗口获得焦点时，确保状态栏为透明
            com.app.input.personalised.board.helpers.StatusBarHelper.INSTANCE.setTransparentStatusBar(this);
        }
    }

    private void initData() {
        // 获取所有数据
        try {
            List<ThemeCategory> viewAllList = BoartApp.Companion.getList();
            for (ThemeCategory wrapper : viewAllList) {
                if (wrapper.getKeyboardList() != null) {
                    allItems.addAll(wrapper.getKeyboardList());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initSearchRecycler() {
        searchAdapter = new RecommendedGridAdapter(this);
        searchAdapter.setForYouList(searchResults);
        
        vb.recyclerSearchResults.setLayoutManager(new GridLayoutManager(this, 2));
        vb.recyclerSearchResults.setAdapter(searchAdapter);
        vb.recyclerSearchResults.addItemDecoration(new GridItemDecoration(2, 2, 0));
        
        // 初始状态显示空结果
        updateSearchUI();
    }

    private void initSearchBar() {
        // 延迟显示键盘，确保界面已加载
        new Handler(Looper.getMainLooper()).postDelayed(() -> {
            vb.etSearch.requestFocus();
            InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
            if (imm != null) {
                imm.showSoftInput(vb.etSearch, InputMethodManager.SHOW_IMPLICIT);
            }
        }, 200);
        
        // 监听输入变化，实时搜索（使用延迟搜索，避免频繁搜索）
        final Handler searchHandler = new Handler(Looper.getMainLooper());
        final Runnable[] searchRunnableRef = new Runnable[1];
        
        vb.etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // 移除之前的搜索任务
                if (searchRunnableRef[0] != null) {
                    searchHandler.removeCallbacks(searchRunnableRef[0]);
                }
                
                // 延迟300ms执行搜索，避免输入时频繁搜索
                final String searchText = s.toString();
                searchRunnableRef[0] = () -> performSearch(searchText);
                searchHandler.postDelayed(searchRunnableRef[0], 300);
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        
        // 监听软键盘搜索按钮
        vb.etSearch.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                performSearch(v.getText().toString());
                // 隐藏键盘
                InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
                return true;
            }
            return false;
        });
    }

    private void initClick() {
        // 返回按钮
        vb.ivBack.setOnClickListener(v -> onInterceptBackPressed());
        
        // 清除按钮
        vb.ivClear.setOnClickListener(v -> {
            vb.etSearch.setText("");
            vb.etSearch.requestFocus();
        });
    }

    private void performSearch(String query) {
        searchResults.clear();
        
        if (query == null || query.trim().isEmpty()) {
            updateSearchUI();
            return;
        }
        
        String searchQuery = query.trim().toLowerCase();
        
        // 模糊搜索：匹配标题
        for (KeyboardTheme item : allItems) {
            String title = item.getTitleName();
            if (title != null && title.toLowerCase().contains(searchQuery)) {
                searchResults.add(item);
            }
        }
        
        updateSearchUI();
    }

    private void updateSearchUI() {
        if (searchResults.isEmpty()) {
            if (vb.etSearch.getText().toString().trim().isEmpty()) {
                // 搜索框为空，显示提示
                vb.tvEmptyHint.setText(getString(R.string.search_hint));
                vb.tvEmptyHint.setVisibility(View.VISIBLE);
                vb.recyclerSearchResults.setVisibility(View.GONE);
            } else {
                // 有搜索内容但无结果
                vb.tvEmptyHint.setText(getString(R.string.no_search_results));
                vb.tvEmptyHint.setVisibility(View.VISIBLE);
                vb.recyclerSearchResults.setVisibility(View.GONE);
            }
        } else {
            // 有搜索结果
            vb.tvEmptyHint.setVisibility(View.GONE);
            vb.recyclerSearchResults.setVisibility(View.VISIBLE);
            searchAdapter.setForYouList(searchResults);
        }
        
        // 根据是否有输入内容显示/隐藏清除按钮
        vb.ivClear.setVisibility(
            vb.etSearch.getText().toString().trim().isEmpty() ? View.GONE : View.VISIBLE
        );
    }


    @Override
    protected boolean shouldInterceptBackPress() {
        return true;
    }

    @Override
    protected void onInterceptBackPressed() {

        TPAdManager.INSTANCE.showTPAD(this, new Function0<Unit>() {
            @Override
            public Unit invoke() {
                return null;
            }
        });
        if (getBackPressedCallback() != null) {
            getBackPressedCallback().setEnabled(false);
        }
        getOnBackPressedDispatcher().onBackPressed();
    }
}

