package com.joyful.euphoria.board.xmlactivity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
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 androidx.recyclerview.widget.RecyclerView;
import com.joyful.euphoria.board.R;
import com.joyful.euphoria.board.recyclerview.RecyclerviewCategory;
import com.joyful.euphoria.board.beaned.BeanDetails;
import com.joyful.euphoria.board.beaned.BeanWrapper;
import com.joyful.euphoria.board.database.CategoryData;
import com.joyful.euphoria.board.database.BoardData;
import com.joyful.euphoria.board.EuphoriaBoard;
import com.joyful.euphoria.board.utils.FileUtils;
import com.joyful.euphoria.board.utils.ListDecorationUtils;
import java.util.ArrayList;
import java.util.List;

public class CategoryXML extends AppCompatActivity {
    private static final String TAG = "CategoryActivity";
    public static final String KEY_CATEGORY_NAME = "category_name";

    private RecyclerView rvCateKeyboard;
    private View llCateEmpty;
    private View ivCateBack;
    private TextView tvCateTitle;
    private RecyclerviewCategory mCateKeyboardAdapter;
    private List<BeanDetails> mKeyboardList = new ArrayList<>();
    private List<CategoryData> mCategoryDataList = new ArrayList<>();
    private String mCurrentCategoryName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_category_xml);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.category), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        initView();
        getIntentData();
        initAdapter();
        loadCategoryData();
        loadKeyboardDataByCategory();
    }

    private void initView() {
        rvCateKeyboard = findViewById(R.id.rv_cate_keyboard);
        llCateEmpty = findViewById(R.id.ll_cate_empty);
        ivCateBack = findViewById(R.id.iv_cate_back);
        tvCateTitle = findViewById(R.id.tv_cate_title);

        ivCateBack.setOnClickListener(v -> finish());
    }

    private void getIntentData() {
        mCurrentCategoryName = getIntent().getStringExtra(KEY_CATEGORY_NAME);
        tvCateTitle.setText(mCurrentCategoryName == null ? "未知分类" : mCurrentCategoryName);
    }

    private void initAdapter() {
        mCateKeyboardAdapter = new RecyclerviewCategory(this, mKeyboardList);
        GridLayoutManager layoutManager = new GridLayoutManager(this, 1);
        rvCateKeyboard.setLayoutManager(layoutManager);
        ListDecorationUtils decoration = new ListDecorationUtils(10, 10, 0);
        rvCateKeyboard.addItemDecoration(decoration);
        rvCateKeyboard.setAdapter(mCateKeyboardAdapter);

        // 键盘点击跳转Set界面
        mCateKeyboardAdapter.setOnCategoryKeyboardClickListener(bean -> {
            if (bean == null || bean.getTitleName() == null) {
                Toast.makeText(CategoryXML.this, "键盘数据异常", Toast.LENGTH_SHORT).show();
                return;
            }
            Intent intent = new Intent(CategoryXML.this, DownloadXML.class);
            intent.putExtra(DownloadXML.SOURCE_KEY, bean);
            intent.putExtra(DownloadXML.NAME_KEY, bean.getTitleName());
            intent.putExtra(DownloadXML.DISPLAY_URL_KEY, bean.getImgPath());
            intent.putExtra(DownloadXML.GIF_KEY, bean.getImgGif());
            intent.putExtra(DownloadXML.THUMB_KEY, bean.getThumbUrl());
            intent.putExtra(DownloadXML.ZIP_URL_KEY, bean.getZipPath());
            startActivity(intent);
        });
    }

    private void loadCategoryData() {
        try {
            mCategoryDataList = FileUtils.readCategoryJsonFromAssets(this, "res.json");
            Log.d(TAG, "加载分类原始数据条数：" + mCategoryDataList.size());
        } catch (Exception e) {
            Log.e(TAG, "加载分类原始数据失败", e);
        }
    }

    private void loadKeyboardDataByCategory() {
        if (mCurrentCategoryName == null || mCategoryDataList.isEmpty()) {
            showEmptyState();
            return;
        }

        mKeyboardList.clear();
        // 从JSON原始数据加载
        for (CategoryData categoryData : mCategoryDataList) {
            if (categoryData == null || !mCurrentCategoryName.equalsIgnoreCase(categoryData.getParent_name())) {
                continue;
            }
            if (categoryData.getKeyboard_list() != null && !categoryData.getKeyboard_list().isEmpty()) {
                for (BoardData boardData : categoryData.getKeyboard_list()) {
                    if (boardData == null) {
                        continue;
                    }
                    BeanDetails bean = new BeanDetails();
                    bean.setTitleName(boardData.getTitle() != null ? boardData.getTitle() : "未知键盘");
                    bean.setThumbUrl(boardData.getThumbUrl() != null ? boardData.getThumbUrl() : "");
                    bean.setImgGif(boardData.getThumbUrlGif() != null ? boardData.getThumbUrlGif() : "");
                    if (boardData.getDetail() != null && boardData.getDetail().getThemeContent() != null) {
                        bean.setImgPath(boardData.getDetail().getThemeContent().getImg() != null ?
                                boardData.getDetail().getThemeContent().getImg() : "");
                        bean.setZipPath(boardData.getDetail().getThemeContent().getAndroidRawZipUrl() != null ?
                                boardData.getDetail().getThemeContent().getAndroidRawZipUrl() : "");
                    } else {
                        bean.setImgPath("");
                        bean.setZipPath("");
                    }
                    mKeyboardList.add(bean);
                }
            }
            break;
        }

        // 备选：从DelightBoard全局数据加载
        if (mKeyboardList.isEmpty() && EuphoriaBoard.list != null && !EuphoriaBoard.list.isEmpty()) {
            for (BeanWrapper wrapper : EuphoriaBoard.list) {
                if (wrapper == null || !mCurrentCategoryName.equals(wrapper.getParentName())) {
                    continue;
                }
                mKeyboardList.addAll(wrapper.getKeyboardList());
                break;
            }
        }

        mCateKeyboardAdapter.notifyDataSetChanged();
        if (mKeyboardList.isEmpty()) {
            showEmptyState();
        } else {
            hideEmptyState();
        }
        Log.d(TAG, "分类[" + mCurrentCategoryName + "]下加载键盘条数：" + mKeyboardList.size());
    }

    private void showEmptyState() {
        rvCateKeyboard.setVisibility(View.GONE);
        llCateEmpty.setVisibility(View.VISIBLE);
    }

    private void hideEmptyState() {
        rvCateKeyboard.setVisibility(View.VISIBLE);
        llCateEmpty.setVisibility(View.GONE);
    }
}