package com.joyful.euphoria.board.frag;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

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

import com.joyful.euphoria.board.R;
import com.joyful.euphoria.board.recyclerview.RecyclerviewDialogCollect;
import com.joyful.euphoria.board.beaned.CateFullData;
import com.joyful.euphoria.board.xmlactivity.DownloadXML;
import com.joyful.euphoria.board.utils.ListDecorationUtils;

public class Category extends DialogFragment {
    private static final String ARG_CATE_DATA = "arg_cate_data";
    private CateFullData mCateFullData;

    // 静态工厂方法：传递参数并创建实例
    public static Category newInstance(CateFullData cateFullData) {
        Category fragment = new Category();
        Bundle args = new Bundle();
        args.putSerializable(ARG_CATE_DATA, cateFullData); // 需确保CateFullData实现Serializable
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 接收传递的分类数据
        if (getArguments() != null) {
            mCateFullData = (CateFullData) getArguments().getSerializable(ARG_CATE_DATA);
        }
    }

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

    private void initView(View view) {
        if (mCateFullData == null) {
            dismiss(); // 无数据则关闭弹窗
            return;
        }

        // 绑定弹窗标题
        TextView tvTitle = view.findViewById(R.id.tv_dialog_title);
        tvTitle.setText(mCateFullData.getCategoryName());

        // 弹窗RecyclerView（两列网格）
        RecyclerView rvDialog = view.findViewById(R.id.rv_dialog_category);
        GridLayoutManager layoutManager = new GridLayoutManager(getContext(), 2);
        rvDialog.setLayoutManager(layoutManager);
        rvDialog.addItemDecoration(new ListDecorationUtils(10, 10, 0));

        // 弹窗适配器
        RecyclerviewDialogCollect dialogAdapter = new RecyclerviewDialogCollect(getContext(), mCateFullData.getKeyboardList());
        rvDialog.setAdapter(dialogAdapter);

        // 弹窗中键盘点击 → 跳转Download+关闭弹窗
        dialogAdapter.setOnKeyboardClickListener(bean -> {
            if (bean == null || bean.getTitleName() == null) {
                Toast.makeText(getActivity(), "键盘数据异常", Toast.LENGTH_SHORT).show();
                return;
            }
            Intent intent = new Intent(getActivity(), 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);
            dismiss(); // 关闭弹窗
        });
    }

    @Override
    public void onStart() {
        super.onStart();
        Dialog dialog = getDialog();
        if (dialog == null) return;

        Window window = dialog.getWindow();
        if (window == null) return;

        // 窗口配置（宽度全屏、底部对齐）
        WindowManager.LayoutParams params = window.getAttributes();
        params.width = WindowManager.LayoutParams.MATCH_PARENT;
        params.gravity = Gravity.BOTTOM;
        params.flags |= WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
        params.flags |= WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR;
        window.setAttributes(params);

        // 适配虚拟按键
        View decorView = window.getDecorView();
        decorView.setOnApplyWindowInsetsListener((v, insets) -> {
            int navBarHeight = insets.getSystemWindowInsetBottom();
            int screenHeight = getResources().getDisplayMetrics().heightPixels;
            int dialogHeight = (int) (screenHeight * 0.75) - navBarHeight;

            WindowManager.LayoutParams layoutParams = window.getAttributes();
            layoutParams.height = dialogHeight;
            window.setAttributes(layoutParams);

            View rootView = getView();
            if (rootView != null) {
                rootView.setPadding(0, 0, 0, navBarHeight);
            }

            return insets.consumeSystemWindowInsets();
        });

        // 设置弹窗背景
        window.setBackgroundDrawableResource(R.drawable.bg_euphoria_dialog_download);
    }
}