package com.paint.sweet.drawing.sweetactivity;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.ad.toponlibrary.AdManager;
import com.paint.sweet.drawing.R;
import com.paint.sweet.drawing.sweetadapter.ImagePreviewListAdapter;
import com.paint.sweet.drawing.sweetmanager.AppUtils;
import com.paint.sweet.drawing.sweetmanager.AppConstants;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class DrawingSearchActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = "SearchActivity";
    private EditText etSearch;
    private RecyclerView rvSearchResult;
    private RecyclerView rvKeywordSuggest;
    private RecyclerView rvHistorySuggest; // 历史搜索列表
    private LinearLayout llBackContainer; // ========== 修改1：扩大返回键点击区域（用容器包裹） ==========
    private TextView tvSearchBtn;
    private ImageView ivClearHistory; // 清除图标
    private TextView tvNoHistory; // 无历史提示文字
    private LinearLayout llHotSearchContainer;
    private LinearLayout llHistorySearchContainer; // 历史搜索容器
    private ImagePreviewListAdapter resultAdapter;
    private KeywordAdapter suggestAdapter;
    private KeywordAdapter historyAdapter; // 历史搜索适配器
    private List<String> allContentList = new ArrayList<>();
    private List<String> allContentListLower = new ArrayList<>();
    private List<String> suggestKeywords = new ArrayList<>();
    private List<String> historyKeywords = new ArrayList<>(); // 历史搜索数据
    private boolean isInSearchResultState = false;

    // SharedPreferences存储历史搜索（持久化）
    private static final String SP_HISTORY_SEARCH = "sp_history_search";
    private static final String KEY_HISTORY_KEYWORDS = "key_history_keywords";
    private static final int MAX_HISTORY_COUNT = 10; // 历史搜索最大数量

    // ========== 核心修改：统一布局参数（和ImagePreviewFragment完全一致） ==========
    private static final int GRID_COLUMN_COUNT = 2; // 列数改为2（和主页面一致）
    private static final int PAGE_PADDING_DP = 15; // 页面内边距改为15dp（和主页面一致）
    private static final int ITEM_SPACING_DP = 12; // Item间距改为12dp（和主页面一致）
    private static final long SEARCH_DEBOUNCE_DELAY = 150;

    private static final List<String> DEFAULT_SUGGEST_KEYWORDS;
    private static final List<String> DEFAULT_SUGGEST_KEYWORDS_LOWER;
    static {
        DEFAULT_SUGGEST_KEYWORDS = new ArrayList<>();
        DEFAULT_SUGGEST_KEYWORDS.add("animals");
        DEFAULT_SUGGEST_KEYWORDS.add("cafe");
        DEFAULT_SUGGEST_KEYWORDS.add("cartoons");
        DEFAULT_SUGGEST_KEYWORDS.add("butterfly");
        DEFAULT_SUGGEST_KEYWORDS.add("nature");
        DEFAULT_SUGGEST_KEYWORDS.add("sports");

        DEFAULT_SUGGEST_KEYWORDS_LOWER = new ArrayList<>();
        for (String keyword : DEFAULT_SUGGEST_KEYWORDS) {
            DEFAULT_SUGGEST_KEYWORDS_LOWER.add(keyword.toLowerCase());
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                window.getDecorView().setSystemUiVisibility(
                        View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                                | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                );
            } else {
                window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            }
            window.setStatusBarColor(getResources().getColor(android.R.color.transparent));
        }
        AppUtils.setStatusBarTextColor(this, false);

        setContentView(R.layout.activity_drawing_search);
        AdManager.loadAllAd();
        AdManager.showTopOn(this, () -> {});
        View rootLayout = findViewById(R.id.root_layout);
        if (rootLayout != null) {
            int statusBarHeight = getStatusBarHeight();
            rootLayout.setPadding(0, statusBarHeight, 0, 0);
        }

        getWindow().getDecorView().postDelayed(() -> {
            initViews();
            initRecyclerViews();
            setSearchIcon();
            loadAllContent();
            loadHistorySearch(); // 加载历史搜索
            setSearchListener();
            handleInitKeyword();
            showSuggestKeywords(DEFAULT_SUGGEST_KEYWORDS); // 始终显示默认热门关键词
            showHistoryKeywords(); // 显示历史搜索
        }, 100);
    }

    private void initRecyclerViews() {
        // 搜索结果列表：完全对齐主页面ImagePreviewFragment的逻辑
        if (rvSearchResult == null) return;
        resultAdapter = new ImagePreviewListAdapter(this, new ArrayList<>(), true);
        rvSearchResult.setAdapter(resultAdapter);

        // 1. 2列网格布局（和主页面一致）
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 2);
        rvSearchResult.setLayoutManager(gridLayoutManager);

        // 2. 页面四周边距：15dp（和主页面搜索栏的start/end margin一致）
        int pagePadding = dp2px(15);
        rvSearchResult.setPadding(pagePadding, pagePadding, pagePadding, pagePadding);
        rvSearchResult.setClipToPadding(false);

        // 3. 计算Item宽度（完全复用主页面Fragment的逻辑）
        int screenWidth = getResources().getDisplayMetrics().widthPixels;
        int usableWidth = screenWidth - pagePadding * 2;
        int itemSpacing = dp2px(12); // 和主页面一致的Item间距
        int itemWidth = (usableWidth - itemSpacing) / 2;

        // 4. Item间距：对称分配（和主页面Fragment完全一致）
        rvSearchResult.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                ViewGroup.LayoutParams params = view.getLayoutParams();
                if (params != null) {
                    params.width = itemWidth;
                    params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
                    view.setLayoutParams(params);
                }

                int position = parent.getChildAdapterPosition(view);
                int column = position % 2;
                int halfSpacing = itemSpacing / 2;

                // 水平对称间距
                if (column == 0) {
                    outRect.left = 0;
                    outRect.right = halfSpacing;
                } else {
                    outRect.left = halfSpacing;
                    outRect.right = 0;
                }

                // 垂直对称间距
                outRect.top = halfSpacing;
                outRect.bottom = halfSpacing;
            }
        });

        // 热门/历史搜索列表逻辑不变（仅调整了布局的padding，代码无需改动）
        if (rvKeywordSuggest == null) return;
        suggestAdapter = new KeywordAdapter(this, new ArrayList<>());
        rvKeywordSuggest.setAdapter(suggestAdapter);
        LinearLayoutManager hotLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
        rvKeywordSuggest.setLayoutManager(hotLayoutManager);
        suggestAdapter.setOnKeywordClickListener(keyword -> {
            etSearch.setText(keyword);
            etSearch.setSelection(keyword.length());
            performSearch(keyword);
        });

        if (rvHistorySuggest == null) return;
        historyAdapter = new KeywordAdapter(this, new ArrayList<>());
        rvHistorySuggest.setAdapter(historyAdapter);
        LinearLayoutManager historyLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
        rvHistorySuggest.setLayoutManager(historyLayoutManager);
        historyAdapter.setOnKeywordClickListener(keyword -> {
            etSearch.setText(keyword);
            etSearch.setSelection(keyword.length());
            performSearch(keyword);
        });
    }


    private void initViews() {
        // 原有控件绑定
        etSearch = findViewById(R.id.et_search);
        rvSearchResult = findViewById(R.id.rv_search_result);
        rvKeywordSuggest = findViewById(R.id.rv_keyword_suggest);
        // ========== 修改2：替换ivBack为llBackContainer（容器） ==========
        llBackContainer = findViewById(R.id.ll_back_container);
        tvSearchBtn = findViewById(R.id.tv_search_btn);
        llHotSearchContainer = findViewById(R.id.ll_hot_search_container);

        // 历史搜索相关控件绑定
        rvHistorySuggest = findViewById(R.id.rv_history_suggest);
        ivClearHistory = findViewById(R.id.iv_clear_history);
        tvNoHistory = findViewById(R.id.tv_no_history);
        llHistorySearchContainer = findViewById(R.id.ll_history_search_container);

        // 日志打印
        Log.d(TAG, "etSearch is null: " + (etSearch == null));
        Log.d(TAG, "rvSearchResult is null: " + (rvSearchResult == null));
        Log.d(TAG, "rvKeywordSuggest is null: " + (rvKeywordSuggest == null));
        Log.d(TAG, "rvHistorySuggest is null: " + (rvHistorySuggest == null));
        Log.d(TAG, "llBackContainer is null: " + (llBackContainer == null)); // 修改日志
        Log.d(TAG, "tvSearchBtn is null: " + (tvSearchBtn == null));
        Log.d(TAG, "ivClearHistory is null: " + (ivClearHistory == null));
        Log.d(TAG, "tvNoHistory is null: " + (tvNoHistory == null));
        Log.d(TAG, "llHotSearchContainer is null: " + (llHotSearchContainer == null));
        Log.d(TAG, "llHistorySearchContainer is null: " + (llHistorySearchContainer == null));

        // 设置无历史搜索提示文字为英文
        if (tvNoHistory != null) {
            tvNoHistory.setText("No search history");
        }

        // ========== 修改3：给llBackContainer设置点击事件（扩大返回键区域） ==========
        if (llBackContainer != null) {
            llBackContainer.setOnClickListener(this);
        }
        if (tvSearchBtn != null) {
            tvSearchBtn.setOnClickListener(this);
        }

        // 清除历史图标按钮点击事件
        if (ivClearHistory != null) {
            ivClearHistory.setOnClickListener(this);
        }
    }

    private void setSearchIcon() {
        if (etSearch == null) {
            Log.e(TAG, "Search input box is null");
            return;
        }
        Drawable searchIcon = ContextCompat.getDrawable(this, R.mipmap.search2);
        if (searchIcon != null) {
            int iconSize = dp2px(18);
            searchIcon.setBounds(0, 0, iconSize, iconSize);
            searchIcon.setTint(Color.parseColor("#CC9E9E9E"));
            etSearch.setCompoundDrawables(searchIcon, null, null, null);
            etSearch.setCompoundDrawablePadding(dp2px(10));
        }
    }

    private void loadAllContent() {
        try {
            allContentList.clear();
            allContentListLower.clear();
            List<String> dirs = AppConstants.getAllDir();
            if (dirs == null || dirs.isEmpty()) {
                Log.e(TAG, "No resource directories");
                return;
            }
            for (String dir : dirs) {
                List<String> files = AppUtils.fileExistsInAssets(this, dir);
                if (files != null && !files.isEmpty()) {
                    allContentList.addAll(files);
                    for (String file : files) {
                        allContentListLower.add(file.toLowerCase());
                    }
                }
            }
            Log.d(TAG, "Total resources: " + allContentList.size());
            resultAdapter.updateData(new ArrayList<>());
        } catch (Exception e) {
            e.printStackTrace();
            Log.e(TAG, "Failed to load resources: " + e.getMessage());
        }
    }

    // 从SharedPreferences加载历史搜索记录
    private void loadHistorySearch() {
        SharedPreferences sp = getSharedPreferences(SP_HISTORY_SEARCH, Context.MODE_PRIVATE);
        Set<String> historySet = sp.getStringSet(KEY_HISTORY_KEYWORDS, new HashSet<>());
        historyKeywords.clear();
        historyKeywords.addAll(historySet);
        // 限制历史记录最大数量
        if (historyKeywords.size() > MAX_HISTORY_COUNT) {
            historyKeywords = historyKeywords.subList(0, MAX_HISTORY_COUNT);
        }
    }

    // 保存历史搜索（去重+置顶+限制数量）
    private void saveHistorySearch(String keyword) {
        if (TextUtils.isEmpty(keyword)) return;
        // 去重：如果已存在则移除，再添加到首位
        historyKeywords.remove(keyword);
        historyKeywords.add(0, keyword);
        // 限制最大数量
        if (historyKeywords.size() > MAX_HISTORY_COUNT) {
            historyKeywords.remove(historyKeywords.size() - 1);
        }
        // 持久化存储
        SharedPreferences sp = getSharedPreferences(SP_HISTORY_SEARCH, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putStringSet(KEY_HISTORY_KEYWORDS, new HashSet<>(historyKeywords));
        editor.apply();
        // 更新UI（仅在非搜索状态下刷新）
        if (!isInSearchResultState) {
            showHistoryKeywords();
        }
    }

    // ========== 新增：补全缺失的clearHistorySearch()方法 ==========
    private void clearHistorySearch() {
        historyKeywords.clear();
        SharedPreferences sp = getSharedPreferences(SP_HISTORY_SEARCH, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.remove(KEY_HISTORY_KEYWORDS);
        editor.apply();
        showHistoryKeywords(); // 刷新UI
        Log.d(TAG, "All search history cleared");
    }

    // 修改：显示历史搜索（仅在非搜索状态下显示）
    private void showHistoryKeywords() {
        if (llHistorySearchContainer == null || rvHistorySuggest == null || tvNoHistory == null || ivClearHistory == null) return;

        // 仅在非搜索状态下显示历史搜索容器
        if (isInSearchResultState) {
            llHistorySearchContainer.setVisibility(View.GONE);
            return;
        }

        llHistorySearchContainer.setVisibility(View.VISIBLE);
        if (historyKeywords.isEmpty()) {
            // 无历史记录：显示提示文字，隐藏列表和清除图标
            rvHistorySuggest.setVisibility(View.GONE);
            tvNoHistory.setVisibility(View.VISIBLE);
            ivClearHistory.setVisibility(View.GONE);
        } else {
            // 有历史记录：显示列表和清除图标，隐藏提示文字
            rvHistorySuggest.setVisibility(View.VISIBLE);
            tvNoHistory.setVisibility(View.GONE);
            ivClearHistory.setVisibility(View.VISIBLE);
            historyAdapter.updateData(historyKeywords);
        }
    }

    // 修改：移除输入框变化时的热门关键词过滤（保持热门搜索不变）
    private void setSearchListener() {
        if (etSearch == null) {
            Log.e(TAG, "Search input box is null");
            return;
        }
        // 仅保留防抖，但不触发关键词过滤（热门搜索始终显示默认值）
        Handler searchHandler = new Handler(Looper.getMainLooper());
        Runnable searchRunnable = new Runnable() {
            @Override
            public void run() {
                // 空实现：不再根据输入过滤热门关键词
            }
        };

        etSearch.addTextChangedListener(new android.text.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) {
                searchHandler.removeCallbacks(searchRunnable);
                searchHandler.postDelayed(searchRunnable, SEARCH_DEBOUNCE_DELAY);
            }

            @Override
            public void afterTextChanged(android.text.Editable s) {}
        });
    }

    // 修改
    private void performSearch(String keyword) {
        List<String> filteredList = new ArrayList<>();
        if (allContentList.isEmpty() || resultAdapter == null) {
            resultAdapter.updateData(filteredList);
            return;
        }
        if (TextUtils.isEmpty(keyword)) {
            // 关键词为空（返回搜索页面）：显示历史+热门搜索
            filteredList = new ArrayList<>();
            isInSearchResultState = false;
            llHistorySearchContainer.setVisibility(View.VISIBLE);
            showHistoryKeywords();
            if (llHotSearchContainer != null) {
                llHotSearchContainer.setVisibility(View.VISIBLE);
            }
        } else {
            // 关键词不为空（搜索中）：隐藏历史+热门搜索，执行搜索
            String lowerKeyword = keyword.toLowerCase().trim();
            for (int i = 0; i < allContentListLower.size(); i++) {
                if (allContentListLower.get(i).contains(lowerKeyword)) {
                    filteredList.add(allContentList.get(i));
                }
            }
            isInSearchResultState = true;
            if (llHistorySearchContainer != null) {
                llHistorySearchContainer.setVisibility(View.GONE);
            }
            if (llHotSearchContainer != null) {
                llHotSearchContainer.setVisibility(View.GONE);
            }
            saveHistorySearch(keyword);
        }
        resultAdapter.updateData(filteredList);
        // 核心修改：搜索无结果时显示提示，且保持输入框文字颜色默认
        if (!TextUtils.isEmpty(keyword)) {
            if (filteredList.isEmpty()) {
                // 显示“找不到结果”提示（英文）
                Toast.makeText(this, "No results found", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "Found " + filteredList.size() + " results", Toast.LENGTH_SHORT).show();
            }
        }
        // 确保输入框文字颜色始终为默认（避免标红）
        if (etSearch != null) {
            etSearch.setTextColor(Color.parseColor("#CC9E9E9E")); // 与布局中textcolor一致
        }
        rvSearchResult.setVisibility(filteredList.size() > 0 ? View.VISIBLE : View.GONE);
        showSuggestKeywords(DEFAULT_SUGGEST_KEYWORDS);
        showHistoryKeywords();
    }


    // 修改：始终显示默认热门关键词
    private void showSuggestKeywords(List<String> keywords) {
        if (suggestAdapter == null || rvKeywordSuggest == null) return;
        if (!isInSearchResultState) {
            // 非搜索状态（返回搜索页面）：显示Popular Search关键词
            suggestAdapter.updateData(DEFAULT_SUGGEST_KEYWORDS);
            rvKeywordSuggest.setVisibility(View.VISIBLE);
        } else {
            rvKeywordSuggest.setVisibility(View.GONE);
        }
    }

    private void handleInitKeyword() {
        String initKeyword = getIntent().getStringExtra("keyword");
        if (!TextUtils.isEmpty(initKeyword) && etSearch != null) {
            etSearch.setText(initKeyword);
            etSearch.setSelection(initKeyword.length());
        }
    }

    // 点击事件处理
    @Override
    public void onClick(View v) {
        int id = v.getId();
        // ========== 修改4：替换iv_back的id为ll_back_container ==========
        if (id == R.id.ll_back_container) {
            AdManager.showTopOn(this, () -> {
                // ========== 修改5：优化返回逻辑（搜索结果页直接返回首页） ==========
                if (isInSearchResultState) {
                    // 当前是搜索结果页：直接返回首页
                    super.onBackPressed();
                    Log.d(TAG, "Current state is search result, return to Home page directly");
                } else {
                    // 当前是搜索初始页：返回上一级
                    super.onBackPressed();
                    Log.d(TAG, "Current state is search initial, return to Home page");
                }
            });

        } else if (id == R.id.tv_search_btn) {
            AdManager.showTopOn(this, () -> {
                String keyword = etSearch.getText().toString().trim();
                performSearch(keyword);
            });

        } else if (id == R.id.iv_clear_history) {
            // 清除历史搜索
            clearHistorySearch();
            Log.d(TAG, "Clear all search history records");
        }
    }

    // ========== 修改6：简化onBackPressed逻辑（和点击事件统一） ==========
    @Override
    public void onBackPressed() {
        onClick(findViewById(R.id.ll_back_container)); // 复用点击事件的逻辑
    }

    private int getStatusBarHeight() {
        int statusBarHeight = 0;
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            statusBarHeight = getResources().getDimensionPixelSize(resourceId);
        }
        if (statusBarHeight == 0) {
            statusBarHeight = dp2px(48);
        }
        return statusBarHeight;
    }

    private int dp2px(int dp) {
        return (int) (dp * getResources().getDisplayMetrics().density + 0.5f);
    }


    // 关键词适配器（复用，同时支持历史/热门搜索）
    private static class KeywordAdapter extends RecyclerView.Adapter<KeywordAdapter.KeywordViewHolder> {
        private Context context;
        private List<String> keywords;
        private OnKeywordClickListener listener;

        public KeywordAdapter(Context context, List<String> keywords) {
            this.context = context;
            this.keywords = keywords;
        }

        public void updateData(List<String> newKeywords) {
            this.keywords.clear();
            this.keywords.addAll(newKeywords);
            notifyDataSetChanged();
        }

        public void setOnKeywordClickListener(OnKeywordClickListener listener) {
            this.listener = listener;
        }

        @NonNull
        @Override
        public KeywordViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(context).inflate(R.layout.item_keyword_suggest, parent, false);
            return new KeywordViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull KeywordViewHolder holder, int position) {
            String keyword = keywords.get(position);
            holder.tvKeyword.setText(keyword);
            holder.itemView.setOnClickListener(v -> {
                if (listener != null) {
                    listener.onKeywordClick(keyword);
                }
            });
        }

        @Override
        public int getItemCount() {
            return keywords.size();
        }

        static class KeywordViewHolder extends RecyclerView.ViewHolder {
            TextView tvKeyword;
            public KeywordViewHolder(@NonNull View itemView) {
                super(itemView);
                tvKeyword = itemView.findViewById(R.id.tv_keyword);
            }
        }

        public interface OnKeywordClickListener {
            void onKeywordClick(String keyword);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().getDecorView().setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                            | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
            );
            AppUtils.setStatusBarTextColor(this, false);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 释放所有控件引用
        etSearch = null;
        rvSearchResult = null;
        rvKeywordSuggest = null;
        rvHistorySuggest = null;
        llBackContainer = null; // 修改释放引用
        tvSearchBtn = null;
        ivClearHistory = null;
        tvNoHistory = null;
        llHotSearchContainer = null;
        llHistorySearchContainer = null;
        resultAdapter = null;
        suggestAdapter = null;
        historyAdapter = null;
        allContentList.clear();
        allContentList = null;
        allContentListLower.clear();
        allContentListLower = null;
        suggestKeywords.clear();
        suggestKeywords = null;
        historyKeywords.clear();
        historyKeywords = null;
    }
}