package com.cake.draw.painting.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatButton;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.cake.draw.painting.CakePaintingApp;
import com.cake.draw.painting.R;
import com.cake.draw.painting.activity.CameraCakeActivity;
import com.cake.draw.painting.activity.SearchCakeActivity;
import com.cake.draw.painting.adapter.HomeCakeAdapter;
import com.cake.draw.painting.databinding.FragmentHomeCakeBinding;
import com.cake.draw.painting.tools.Keys;
import com.cake.draw.painting.tools.Utils;
import com.cake.draw.painting.onClickListener;

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

public class HomeCakeFragment extends Fragment implements onClickListener {
    private static final String TAG = "HomeFragment";
    private FragmentHomeCakeBinding fragmentHomeBinding;
    private List<String> allCategoryDirs;
    private AppCompatButton selectedButton;
    private HomeCakeAdapter homeCakeAdapter;
    // 加载状态标记
    private boolean isLoading = false;

    public HomeCakeFragment() {
    }

    public static HomeCakeFragment newInstance() {
        return new HomeCakeFragment();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        allCategoryDirs = Keys.getAllDir();
        if (allCategoryDirs == null) {
            allCategoryDirs = new ArrayList<>();
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        fragmentHomeBinding = FragmentHomeCakeBinding.inflate(inflater, container, false);
        initCategoryButtons();
        initRecycler();
        initSearch(); // 初始化搜索图标跳转逻辑

        // 初始化时加载第一个分类的数据（关键：补充默认加载）
        if (!allCategoryDirs.isEmpty()) {
            loadCategoryData(allCategoryDirs.get(0));
        }

        return fragmentHomeBinding.getRoot();
    }

    /**
     * 初始化分类按钮栏
     */
    private void initCategoryButtons() {
        LinearLayout buttonContainer = fragmentHomeBinding.llCategoryButtons;
        buttonContainer.removeAllViews();

        for (int i = 0; i < allCategoryDirs.size(); i++) {
            String dir = allCategoryDirs.get(i);
            String categoryName = dir.contains("_") ? dir.substring(dir.lastIndexOf("_") + 1) : dir;

            AppCompatButton btn = new AppCompatButton(requireContext());
            btn.setText(categoryName);
            btn.setTextSize(14);
            // dp转px适配
            int paddingHorizontal = dp2px(16);
            int paddingVertical = dp2px(8);
            btn.setPadding(paddingHorizontal, paddingVertical, paddingHorizontal, paddingVertical);
            btn.setBackgroundResource(R.drawable.selector_btn_category_cake);
            btn.setTextColor(getResources().getColorStateList(R.color.selector_btn_text_cake));

            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT
            );
            params.setMargins(dp2px(8), 0, dp2px(8), 0);
            btn.setLayoutParams(params);

            int finalI = i;
            btn.setOnClickListener(v -> {
                if (selectedButton != null) {
                    selectedButton.setSelected(false);
                }
                btn.setSelected(true);
                selectedButton = btn;

                String targetDir = allCategoryDirs.get(finalI);
                if (targetDir == null || targetDir.isEmpty()) {
                    Toast.makeText(requireContext(), R.string.invalid_category, Toast.LENGTH_SHORT).show();
                    return;
                }

                // 关键：点击分类按钮时加载对应数据
                loadCategoryData(targetDir);
            });

            buttonContainer.addView(btn);

            // 默认选中第一个按钮
            if (i == 0) {
                btn.setSelected(true);
                selectedButton = btn;
            }
        }
    }

    /**
     * 初始化RecyclerView
     */
    private void initRecycler() {
        homeCakeAdapter = new HomeCakeAdapter(requireContext());
        homeCakeAdapter.setListener(this::onClickItem);

        GridLayoutManager gridLayoutManager = new GridLayoutManager(requireContext(), 3);
        gridLayoutManager.setOrientation(GridLayoutManager.VERTICAL);
        fragmentHomeBinding.recyclerview.setLayoutManager(gridLayoutManager);

        fragmentHomeBinding.recyclerview.addItemDecoration(new GridSpacingItemDecoration(3, dp2px(12), true));
        fragmentHomeBinding.recyclerview.setHasFixedSize(true);
        fragmentHomeBinding.recyclerview.setItemAnimator(null);
        fragmentHomeBinding.recyclerview.setAdapter(homeCakeAdapter);
    }

    /**
     * 初始化搜索图标：点击跳转到SearchActivity
     */
    private void initSearch() {
        fragmentHomeBinding.ivSearch.setOnClickListener(v -> {
            // 跳转到SearchActivity
            Intent intent = new Intent(requireContext(), SearchCakeActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
            startActivity(intent);
        });
    }

    /**
     * 加载指定分类的数据（关键：补充完整的加载逻辑）
     * @param dir 分类目录
     */
    private void loadCategoryData(String dir) {
        if (isLoading) {
            return; // 防止重复加载
        }
        isLoading = true;
        showLoading(true); // 显示加载中
        showEmptyState(false); // 加载时隐藏空状态

        // 异步加载Assets中的图片路径（避免主线程阻塞）
        new Thread(() -> {
            try {
                // 模拟加载耗时（实际项目可移除，仅为用户体验）
                Thread.sleep(300);

                // 从Assets获取指定目录下的所有图片路径
                List<String> imagePaths = Utils.getImagePathsByDir(requireContext(), dir);
                Log.d(TAG, "分类：" + dir + "，图片数量：" + (imagePaths == null ? 0 : imagePaths.size()));

                // 切回主线程更新UI
                requireActivity().runOnUiThread(() -> {
                    isLoading = false;
                    showLoading(false); // 隐藏加载中

                    if (imagePaths == null || imagePaths.isEmpty()) {
                        // 无数据时显示空状态
                        showEmptyState(true);
                        homeCakeAdapter.setData(new ArrayList<>()); // 传递空列表避免空指针
                        Toast.makeText(requireContext(), R.string.no_sketches_found, Toast.LENGTH_SHORT).show();
                    } else {
                        // 有数据时更新Adapter
                        showEmptyState(false);
                        homeCakeAdapter.setData(imagePaths); // 给Adapter设置图片路径列表
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
                requireActivity().runOnUiThread(() -> {
                    isLoading = false;
                    showLoading(false);
                    showEmptyState(true); // 加载失败也显示空状态
                    homeCakeAdapter.setData(new ArrayList<>());
                    Toast.makeText(requireContext(), R.string.load_data_failed, Toast.LENGTH_SHORT).show();
                });
            }
        }).start();
    }

    /**
     * 显示/隐藏加载状态
     */
    private void showLoading(boolean show) {
        fragmentHomeBinding.progressLoading.setVisibility(show ? View.VISIBLE : View.GONE);
    }

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

    /**
     * 图片Item点击跳转
     */
    @Override
    public void onClickItem(boolean viewAll, String dir) {
        if (dir == null || dir.isEmpty()) {
            Toast.makeText(requireContext(), R.string.invalid_directory, Toast.LENGTH_SHORT).show();
            return;
        }
        Intent intent = new Intent(requireContext(), 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);
    }

    /**
     * 网格间距装饰器
     */
    public static class GridSpacingItemDecoration extends RecyclerView.ItemDecoration {
        private int spanCount;
        private int spacing;
        private boolean includeEdge;

        public GridSpacingItemDecoration(int spanCount, int spacing, boolean includeEdge) {
            this.spanCount = spanCount;
            this.spacing = spacing;
            this.includeEdge = includeEdge;
        }

        @Override
        public void getItemOffsets(@NonNull android.graphics.Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
            int position = parent.getChildAdapterPosition(view);
            if (position == RecyclerView.NO_POSITION) return;
            int column = position % spanCount;

            if (includeEdge) {
                outRect.left = spacing - column * spacing / spanCount;
                outRect.right = (column + 1) * spacing / spanCount;
                outRect.top = position < spanCount ? spacing : spacing / 2;
                outRect.bottom = spacing;
            } else {
                outRect.left = column * spacing / spanCount;
                outRect.right = spacing - (column + 1) * spacing / spanCount;
                outRect.top = position >= spanCount ? spacing : 0;
                outRect.bottom = spacing;
            }
        }
    }

    /**
     * 防止内存泄漏
     */
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        fragmentHomeBinding = null;
        selectedButton = null;
        homeCakeAdapter = null;
        allCategoryDirs = null;
    }
}