package com.flowing.light.board.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.Button;
import android.widget.LinearLayout;

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

import com.flowing.light.board.FlowingLightBoard;
import com.flowing.light.board.R;
import com.flowing.light.board.adapter.HomeAdapter;
import com.flowing.light.board.bean.BeanDetails;
import com.flowing.light.board.bean.BeanWrapper;
import com.flowing.light.board.databinding.FragmentHomeBinding;
import com.flowing.light.board.activity.SetActivity;
import com.flowing.light.board.tools.CategoryData;
import com.flowing.light.board.tools.FileUtils;
import com.flowing.light.board.tools.KeyboardData;

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

public class FragmentHome extends Fragment {
    private FragmentHomeBinding vb;
    private List<BeanWrapper> allWrapperList; // 原有分类包装数据
    private List<BeanDetails> currentKeyboardList; // 当前分类下的键盘数据
    private HomeAdapter keyboardAdapter;
    private Button selectedCategoryBtn;

    // JSON解析的分类数据（核心修改：类型匹配）
    private List<CategoryData> categoryDataList = new ArrayList<>();
    // 提取的分类名称列表（用于按钮显示）
    private List<String> categoryNameList = new ArrayList<>();



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

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        vb = FragmentHomeBinding.inflate(inflater, container, false);

        // 步骤1：初始化原有数据源
        initData();
        // 步骤2：读取并解析JSON分类文件
        readCategoryJson();
        // 步骤3：初始化分类按钮（从JSON提取分类名）
        initCategoryButtons();
        // 步骤4：初始化键盘列表
        initKeyboardRecyclerView();

        return vb.getRoot();
    }

    /**
     * 初始化原有数据源（FlowingLightBoard）
     */
    private void initData() {
        // 兜底：防止FlowingLightBoard.list为空
        allWrapperList = FlowingLightBoard.list != null ? FlowingLightBoard.list : new ArrayList<>();
        currentKeyboardList = new ArrayList<>();
    }

    /**
     * 读取并解析assets中的JSON分类文件（核心修复：类型匹配）
     */
    private void readCategoryJson() {
        try {
            categoryDataList = FileUtils.readCategoryJsonFromAssets(requireContext(), "res.json");
            Log.d("FragmentHome", "JSON数据读取数量：" + categoryDataList.size()); // 检查是否有数据

            // 提取分类名称（去重+过滤空值）
            for (CategoryData data : categoryDataList) {
                if (data != null && data.getParent_name() != null && !data.getParent_name().trim().isEmpty()) {
                    String cateName = data.getParent_name().trim().toUpperCase();
                    if (!categoryNameList.contains(cateName)) {
                        categoryNameList.add(cateName);
                    }
                }
            }
            // 加载第一个分类的键盘数据
            if (!categoryNameList.isEmpty()) {
                filterKeyboardsByCategory(categoryNameList.get(0));
            }

        } catch (Exception e) {
            Log.e("FragmentHome", "JSON读取失败", e);
        }


    }

    /**
     * 初始化顶部分类按钮（动态创建，全防护）
     */
    private void initCategoryButtons() {
        LinearLayout container = vb.categoryContainer;
        container.removeAllViews();

        LinearLayout.LayoutParams btnParams = new LinearLayout.LayoutParams(
                dp2px(90),
                dp2px(36)
        );
        btnParams.setMargins(dp2px(8), dp2px(12), dp2px(8), dp2px(12));



        for (int i = 0; i < categoryNameList.size(); i++) {
            String category = categoryNameList.get(i);
            Button btn = new Button(requireContext());
            btn.setLayoutParams(btnParams);
            btn.setBackgroundResource(R.drawable.selector_category_btn_light);
            btn.setText(category);
            btn.setTextSize(14);
            btn.setTextColor(getResources().getColor(R.color.black));
            btn.setAllCaps(false);

            // 添加内边距（左、上、右、下），单位为dp
            int paddingLeftRight = dp2px(12); // 左右内边距
            int paddingTopBottom = dp2px(8);  // 上下内边距
            btn.setPadding(paddingLeftRight, paddingTopBottom, paddingLeftRight, paddingTopBottom);

            // 默认选中第一个分类
            if (i == 0) {
                btn.setSelected(true);
                selectedCategoryBtn = btn;
            }

            // 分类按钮点击事件
            btn.setOnClickListener(v -> {
                if (selectedCategoryBtn != null) {
                    selectedCategoryBtn.setSelected(false);
                }
                btn.setSelected(true);
                selectedCategoryBtn = btn;

                // 筛选对应分类的键盘数据
                filterKeyboardsByCategory(category);
                keyboardAdapter.notifyDataSetChanged();


            });

            container.addView(btn);
        }
    }

    /**
     * 核心：根据分类筛选键盘数据（兼容JSON和原有BeanWrapper）
     */
    private void filterKeyboardsByCategory(String targetCategory) {
        currentKeyboardList.clear();
        if (targetCategory == null || targetCategory.trim().isEmpty()) {
            return;
        }

        // 优先从JSON解析的CategoryData中获取数据
        boolean hasJsonData = false;
        for (CategoryData cateData : categoryDataList) {
            // 1. 修复：匹配分类名称（忽略大小写）
            if (cateData != null && targetCategory.equalsIgnoreCase(cateData.getParent_name())) {
                // 2. 修复：判断键盘列表非空（避免空指针）
                if (cateData.getKeyboard_list() != null && !cateData.getKeyboard_list().isEmpty()) {
                    // 3. 修复：内部类引用（KeyboardData首字母大写，与定义一致）
                    for (KeyboardData keyboardData : cateData.getKeyboard_list()) {
                        if (keyboardData == null) continue; // 空值防护

                        BeanDetails bean = new BeanDetails();
                        // 4. 修复：字段拼写错误（getTitte→getTitle，getThumbUrt→getThumbUrl等）
                        bean.setTitleName(keyboardData.getTitle()); // 修复：getTitte()→getTitle()
                        bean.setThumbUrl(keyboardData.getThumbUrl()); // 修复：getThumbUrt()→getThumbUrl()
                        bean.setImgGif(keyboardData.getThumbUrlGif()); // 修复：getThumbUrLGif()→getThumbUrlGif()

                        // 5. 修复：语法不完整（补充括号，方法调用加()）
                        if (keyboardData.getDetail() != null && keyboardData.getDetail().getThemeContent() != null) {
                            bean.setImgPath(keyboardData.getDetail().getThemeContent().getImg());
                            // 修复：getAndroidRawZipUrl→getAndroidRawZipUrl()（加方法括号）
                            bean.setZipPath(keyboardData.getDetail().getThemeContent().getAndroidRawZipUrl());
                        }

                        currentKeyboardList.add(bean);
                    }
                    hasJsonData = true;
                }
                break; // 分类唯一，匹配后退出循环
            }
        }

        // JSON中无数据时，从原有BeanWrapper中获取
        if (!hasJsonData) {
            for (BeanWrapper wrapper : allWrapperList) {
                if (wrapper != null && targetCategory.equalsIgnoreCase(wrapper.getParentName())) {
                    if (wrapper.getKeyboardList() != null) {
                        currentKeyboardList.addAll(wrapper.getKeyboardList());
                    }
                    break;
                }
            }
        }
    }

    /**
     * 初始化键盘列表
     */
    private void initKeyboardRecyclerView() {
        keyboardAdapter = new HomeAdapter(requireContext(), currentKeyboardList);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(requireContext(), 1);
        vb.keyboardRecyclerView.setLayoutManager(gridLayoutManager);
        vb.keyboardRecyclerView.setAdapter(keyboardAdapter);

        // 键盘Item点击事件
        keyboardAdapter.setOnItemClickListener(bean -> {
            if (bean == null || getActivity() == null) {
                return;
            }
            Intent intent = new Intent(getActivity(), SetActivity.class);
            intent.putExtra(SetActivity.SOURCE_KEY, bean); // 传递完整的BeanDetails对象
            intent.putExtra(SetActivity.NAME_KEY, bean.getTitleName());
            intent.putExtra(SetActivity.DISPLAY_URL_KEY, bean.getImgPath());
            intent.putExtra(SetActivity.GIF_KEY, bean.getImgGif());
            intent.putExtra(SetActivity.THUMB_KEY, bean.getThumbUrl());
            intent.putExtra(SetActivity.ZIP_URL_KEY, bean.getZipPath());
            startActivity(intent);
        });
    }

    /**
     * dp转px（增加空值防护）
     */
    private int dp2px(int dp) {
        if (getActivity() == null || getResources() == null) {
            return dp;
        }
        float density = getResources().getDisplayMetrics().density;
        return (int) (dp * density + 0.5f);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        vb = null; // 释放DataBinding引用
    }
}