package com.joyful.euphoria.board.frag;

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 androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.joyful.euphoria.board.R;
import com.joyful.euphoria.board.recyclerview.RecyclerviewHomePage;
import com.joyful.euphoria.board.beaned.BeanDetails;
import com.joyful.euphoria.board.beaned.CateFullData;
import com.joyful.euphoria.board.database.CategoryData;
import com.joyful.euphoria.board.database.BoardData;
import com.joyful.euphoria.board.xmlactivity.DownloadXML;
import com.joyful.euphoria.board.utils.FileUtils;
import com.joyful.euphoria.board.utils.ListDecorationUtils;

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

public class HomePage extends Fragment {
    private static final String TAG = "FragmentHome";
    private RecyclerView rvHomeCategory;
    private View llHomeEmpty;
    private RecyclerviewHomePage mAdapter;
    private List<CateFullData> mCateFullList = new ArrayList<>();

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

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.frag_home_page, container, false);
        initView(rootView);
        initAdapter();
        loadHomeCategoryData();
        return rootView;
    }

    private void initView(View rootView) {
        rvHomeCategory = rootView.findViewById(R.id.rv_home_category);
        llHomeEmpty = rootView.findViewById(R.id.ll_home_empty);
    }

    private void initAdapter() {
        mAdapter = new RecyclerviewHomePage(getContext(), mCateFullList);
        // 主布局网格布局
        GridLayoutManager layoutManager = new GridLayoutManager(getContext(), 2);
        rvHomeCategory.setLayoutManager(layoutManager);
        rvHomeCategory.addItemDecoration(new ListDecorationUtils(10, 10, 0));
        rvHomeCategory.setAdapter(mAdapter);

        // 分类标题/箭头点击 → 显示弹窗
        mAdapter.setOnCateTitleClickListener(cateFullData -> {
            showCategoryDialog(cateFullData);
        });

        // 键盘图片点击 → 跳转Download界面
        mAdapter.setOnKeyboardImgClickListener(bean -> {
            jumpToDownloadActivity(bean);
        });
    }

    // 加载分类完整数据（含所有键盘）
    private void loadHomeCategoryData() {
        try {
            List<CategoryData> categoryDataList = FileUtils.readCategoryJsonFromAssets(getContext(), "res.json");
            if (categoryDataList == null || categoryDataList.isEmpty()) {
                showEmptyState();
                return;
            }

            mCateFullList.clear();
            for (CategoryData categoryData : categoryDataList) {
                if (categoryData == null || categoryData.getParent_name() == null) continue;

                String cateName = categoryData.getParent_name().trim();
                if (cateName.isEmpty()) continue;

                // 转换为BeanDetails列表
                List<BeanDetails> keyboardList = convertToBeanDetails(categoryData.getKeyboard_list());
                if (keyboardList.isEmpty()) continue;

                // 添加完整分类数据
                mCateFullList.add(new CateFullData(cateName, keyboardList));
            }

            mAdapter.notifyDataSetChanged();
            hideEmptyState();
        } catch (Exception e) {
            Log.e(TAG, "加载Home分类数据失败", e);
            showEmptyState();
        }
    }

    // 将BoardData列表转换为BeanDetails列表
    private List<BeanDetails> convertToBeanDetails(List<BoardData> boardDataList) {
        List<BeanDetails> detailsList = new ArrayList<>();
        if (boardDataList == null) return detailsList;

        for (BoardData boardData : boardDataList) {
            if (boardData == null) continue;

            BeanDetails details = new BeanDetails();
            details.setTitleName(boardData.getTitle());
            // 提取图片路径和下载链接
            if (boardData.getDetail() != null && boardData.getDetail().getThemeContent() != null) {
                details.setImgPath(boardData.getDetail().getThemeContent().getImg());
                String zipUrl = boardData.getDetail().getThemeContent().getAndroidRawZipUrl();
                details.setZipUrl(zipUrl != null ? zipUrl.trim() : "");
            }
            details.setThumbUrl(boardData.getThumbUrl());
            detailsList.add(details);
        }
        return detailsList;
    }

    // 显示分类弹窗
    private void showCategoryDialog(CateFullData cateFullData) {
        Category dialog = Category.newInstance(cateFullData);
        dialog.show(getChildFragmentManager(), "CategoryDialog");
    }

    // 跳转Download界面
    private void jumpToDownloadActivity(BeanDetails bean) {
        if (getActivity() == null || bean == null) return;
        Intent intent = new Intent(getActivity(), DownloadXML.class);

        intent.putExtra(DownloadXML.ZIP_URL_KEY, bean.getZipUrl());
        intent.putExtra(DownloadXML.DISPLAY_URL_KEY, bean.getImgPath());
        intent.putExtra(DownloadXML.ZIP_URL_KEY, bean.getZipPath());
        intent.putExtra(DownloadXML.NAME_KEY, bean.getTitleName());
        intent.putExtra(DownloadXML.KEYBOARD_ID, bean.getId());
        intent.putExtra(DownloadXML.KEYBOARD_IMG, bean.getImgPath());
        intent.putExtra(DownloadXML.SOURCE_KEY, bean);
        startActivity(intent);
    }

    // 空状态控制
    private void showEmptyState() {
        rvHomeCategory.setVisibility(View.GONE);
        llHomeEmpty.setVisibility(View.VISIBLE);
    }

    private void hideEmptyState() {
        rvHomeCategory.setVisibility(View.VISIBLE);
        llHomeEmpty.setVisibility(View.GONE);
    }
}