package com.artisanic.helper.artui;

import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Toast;

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 com.artisanic.helper.artadapter.SearchAdapter;
import com.artisanic.helper.test.R;
import com.artisanic.helper.test.databinding.SearchLayoutBinding;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class SearchActivity extends AppCompatActivity {

    private SearchLayoutBinding binding;
    private SearchAdapter mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = SearchLayoutBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        EdgeToEdge.enable(this);
        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;
        });
        initRecyclerView();
        bindEvents();
    }

    private void initRecyclerView() {
        GridLayoutManager layoutManager = new GridLayoutManager(this, 2);
        binding.rvSearchResult.setLayoutManager(layoutManager);
        mAdapter = new SearchAdapter(this, new ArrayList<>());
        binding.rvSearchResult.setAdapter(mAdapter);
    }
    private void bindEvents() {
        binding.imageviewBack.setOnClickListener(v -> finish());
        binding.btnSearch.setOnClickListener(v -> performSearch());
        binding.etSearch.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                performSearch();
                return true;
            }
            return false;
        });
    }
    private void performSearch() {
        // 1. 获取输入的分类名称
        String category = binding.etSearch.getText().toString().trim();
        if (category.isEmpty()) {
            Toast.makeText(this, getString(R.string.please_input_keyword), Toast.LENGTH_SHORT).show();
            return;
        }

        binding.searchPb.setVisibility(View.VISIBLE);
        binding.emptyLayout.setVisibility(View.GONE);
        binding.rvSearchResult.setVisibility(View.GONE);
        new Thread(() -> {
            List<String> imagePathList = getAssetsImageList(category);
            runOnUiThread(() -> {
                binding.searchPb.setVisibility(View.GONE);
                if (imagePathList.isEmpty()) {
                    binding.emptyLayout.setVisibility(View.VISIBLE);
                    Toast.makeText(this, getString(R.string.no_search_result), Toast.LENGTH_SHORT).show();
                } else {
                    binding.rvSearchResult.setVisibility(View.VISIBLE);
                    mAdapter.updateData(imagePathList);
                }
            });
        }).start();
    }
    private List<String> getAssetsImageList(String inputCategory) {
        List<String> imageList = new ArrayList<>();
        try {
            String[] allAssetDirs = getAssets().list("");
            if (allAssetDirs == null || allAssetDirs.length == 0) {
                return imageList;
            }
            String targetDir = null;
            String lowerInput = inputCategory.toLowerCase();
            for (String dir : allAssetDirs) {
                String dirSuffix = dir.replaceFirst("^png_", "").toLowerCase();
                if (dirSuffix.equals(lowerInput)) {
                    targetDir = dir;
                    break;
                }
            }

            if (targetDir == null) {
                return imageList;
            }

            String[] files = getAssets().list(targetDir);
            if (files != null && files.length > 0) {
                for (String fileName : files) {
                    String lowerFileName = fileName.toLowerCase();
                    if (lowerFileName.endsWith(".png") || lowerFileName.endsWith(".jpg")
                            || lowerFileName.endsWith(".jpeg") || lowerFileName.endsWith(".webp")) {
                        imageList.add(targetDir + "/" + fileName);
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            runOnUiThread(() -> Toast.makeText(this, getString(R.string.Assets), Toast.LENGTH_SHORT).show());
        }
        return imageList;
    }
}