package com.cake.draw.painting.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

import com.ad.tradpluslibrary.TPAdManager;
import com.cake.draw.painting.CakePaintingApp;
import com.cake.draw.painting.R;
import com.cake.draw.painting.adapter.HomeCakeAdapter;
import com.cake.draw.painting.databinding.ActivitySearchCakeBinding;
import com.cake.draw.painting.fragment.HomeCakeFragment;
import com.cake.draw.painting.onClickListener;
import com.cake.draw.painting.tools.Keys;
import com.cake.draw.painting.tools.Utils;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

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

public class SearchCakeActivity extends BaseActivity implements onClickListener {
    private ActivitySearchCakeBinding binding;
    private HomeCakeAdapter searchAdapter;
    private ExecutorService executorService; // 异步线程池（避免主线程阻塞）
    private boolean isSearching = false; // 防止重复搜索

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 启用EdgeToEdge
        EdgeToEdge.enable(this);
        // 绑定布局（ViewBinding方式）
        binding = ActivitySearchCakeBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.search), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        TPAdManager.INSTANCE.loadAllAd(this);
        // 初始化控件
        initView();
        // 初始化RecyclerView
        initRecycler();
        // 初始化搜索事件
        initSearchEvent();
        // 初始化返回按钮
        initBackButton();
    }

    /**
     * 初始化基础控件
     */
    private void initView() {
        // 隐藏初始状态的空布局和加载进度条
        binding.emptyLayout.setVisibility(View.GONE);
        binding.searchPb.setVisibility(View.GONE);
        // 给输入框设置默认提示
        binding.etSearch.setHint(getString(R.string.search_sketches));
    }

    /**
     * 初始化RecyclerView（搜索结果列表）
     */
    private void initRecycler() {
        // 使用和HomeFragment相同的Adapter（也可自定义SearchAdapter）
        searchAdapter = new HomeCakeAdapter(this);
        searchAdapter.setListener(this::onClickItem);

        // 网格布局（3列，和首页保持一致）
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 3);
        gridLayoutManager.setOrientation(RecyclerView.VERTICAL);
        binding.resultRecycler.setLayoutManager(gridLayoutManager);

        // 添加网格间距（复用HomeFragment的装饰器）
        binding.resultRecycler.addItemDecoration(new HomeCakeFragment.GridSpacingItemDecoration(
                3, dp2px(12), true));
        binding.resultRecycler.setHasFixedSize(true);
        binding.resultRecycler.setItemAnimator(null);
        binding.resultRecycler.setAdapter(searchAdapter);
    }

    /**
     * 初始化搜索事件（输入框回车 + 搜索按钮点击）
     */
    private void initSearchEvent() {
        // 1. 搜索按钮点击事件
        binding.btnSearch.setOnClickListener(v -> performSearch());

        // 2. 输入框回车触发搜索
        binding.etSearch.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                performSearch();
                // 隐藏软键盘
                hideKeyboard();
                return true;
            }
            return false;
        });
    }

    /**
     * 初始化返回按钮
     */
    private void initBackButton() {
        binding.imBack.setOnClickListener(v -> {
            // 返回上一页（销毁当前Activity）
            onInterceptBackPressed();
        });
    }

    /**
     * 执行搜索逻辑
     */
    private void performSearch() {
        // 防止重复搜索
        if (isSearching) {
            return;
        }

        // 获取搜索关键词
        String keyword = binding.etSearch.getText().toString().trim();
        if (TextUtils.isEmpty(keyword)) {
            Toast.makeText(this, R.string.please_input_search_keyword, Toast.LENGTH_SHORT).show();
            return;
        }

        // 显示加载状态
        showLoading(true);
        // 隐藏空布局
        binding.emptyLayout.setVisibility(View.GONE);

        // 异步搜索（避免主线程阻塞Assets文件遍历）
        if (executorService == null) {
            executorService = Executors.newSingleThreadExecutor();
        }
        executorService.execute(() -> {
            // 模拟搜索耗时（实际可移除）
            try {
                Thread.sleep(300);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            // 核心：遍历Assets所有目录，匹配包含关键词的图片路径
            List<String> allImagePaths = new ArrayList<>();
            // 替换为实际的全量目录（如Keys.getAllDir()）
            List<String> allDirs = Keys.getAllDir();
            if (allDirs != null) {
                for (String dir : allDirs) {
                    List<String> dirImagePaths = Utils.getImagePathsByDir(this, dir);
                    for (String path : dirImagePaths) {
                        // 匹配规则：路径/文件名包含关键词（不区分大小写）
                        if (path.toLowerCase().contains(keyword.toLowerCase())) {
                            allImagePaths.add(path);
                        }
                    }
                }
            }

            // 切回主线程更新UI
            runOnUiThread(() -> {
                isSearching = false;
                showLoading(false);

                if (allImagePaths.isEmpty()) {
                    // 无搜索结果：显示空布局
                    showEmptyState(true);
                    searchAdapter.setData(new ArrayList<>());
                } else {
                    // 有搜索结果：更新Adapter
                    showEmptyState(false);
                    searchAdapter.setData(allImagePaths);
                }
            });
        });
    }

    /**
     * 显示/隐藏加载状态
     */
    private void showLoading(boolean show) {
        isSearching = show;
        binding.searchPb.setVisibility(show ? View.VISIBLE : View.GONE);
        binding.resultRecycler.setVisibility(show ? View.GONE : View.VISIBLE);
    }

    /**
     * 显示/隐藏空状态
     */
    private void showEmptyState(boolean show) {
        binding.emptyLayout.setVisibility(show ? View.VISIBLE : View.GONE);
        binding.resultRecycler.setVisibility(show ? View.GONE : View.VISIBLE);
    }

    /**
     * 隐藏软键盘
     */
    private void hideKeyboard() {
        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        if (imm.isActive() && getCurrentFocus() != null) {
            imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
        }
    }

    /**
     * 搜索结果Item点击跳转
     */
    @Override
    public void onClickItem(boolean viewAll, String dir) {
        if (TextUtils.isEmpty(dir)) {
            Toast.makeText(this, R.string.invalid_directory, Toast.LENGTH_SHORT).show();
            return;
        }
        // 跳转到CameraActivity（和首页Item点击逻辑一致）
        Intent intent = new Intent(this, CameraCakeActivity.class);
        intent.putExtra(CakePaintingApp.Key_Camera, dir);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        startActivity(intent);
    }

    /**
     * dp转px适配
     */
    private int dp2px(int dp) {
        return (int) (getResources().getDisplayMetrics().density * dp + 0.5f);
    }

    /**
     * 释放资源（防止内存泄漏）
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 关闭线程池
        if (executorService != null && !executorService.isShutdown()) {
            executorService.shutdown();
        }
        // 解绑ViewBinding
        binding = null;
        searchAdapter = null;
    }


    @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();
    }
}