package com.rainbow.app.keyboard.uiactivity;

import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.View;
import android.view.ViewTreeObserver;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
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.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.rainbow.app.keyboard.App;
import com.rainbow.app.keyboard.R;
import com.rainbow.app.keyboard.javabean.DetailsjavaBean;
import com.rainbow.app.keyboard.javabean.WrapperjavaBean;
import com.rainbow.app.keyboard.myadapter.KBItemAdapter;
import com.rainbow.app.keyboard.myadapter.NavCategoryAdapter;
import com.rainbow.app.keyboard.databinding.ActivityMainBinding;

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

public class MainActivity extends AppCompatActivity {

    private ActivityMainBinding binding;
    private List<WrapperjavaBean> categoryList;
    private KBItemAdapter keyboardAdapter;
    private NavCategoryAdapter navAdapter;
    private List<DetailsjavaBean> firstCategoryKeyboards;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        EdgeToEdge.enable(this);
        setContentView(binding.getRoot());

        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        initViews();
        initData();
        setupNavigationSidebar();
        setupClickListeners();
        setupScrollListener();
    }

    private void initViews() {
        // 设置应用名称字体
        binding.appName.setTypeface(Typeface.create(binding.appName.getTypeface(), Typeface.BOLD));
    }

    private void initData() {
        // 获取所有分类
        categoryList = new ArrayList<>(App.list);

        // 初始化成员变量，而不是局部变量
        firstCategoryKeyboards = new ArrayList<>();
        if (!categoryList.isEmpty()) {
            firstCategoryKeyboards = categoryList.get(0).getKeyboardList();
        }

        keyboardAdapter = new KBItemAdapter(this);
        keyboardAdapter.setSpanCount(2); // 每行显示两个

        // 先应用配置（使用默认值）
        keyboardAdapter.applyMainActivityConfig();

        // 设置RecyclerView（键盘壁纸网格）
        GridLayoutManager layoutManager = new GridLayoutManager(this, 2);
        binding.recyclerview.setLayoutManager(layoutManager);
        binding.recyclerview.setAdapter(keyboardAdapter);
        binding.recyclerview.setClipToPadding(false);
        binding.recyclerview.setPadding(0, 0, 0, 0);

        // 使用ViewTreeObserver确保在布局完成后设置宽度
        binding.recyclerview.getViewTreeObserver().addOnGlobalLayoutListener(
                new ViewTreeObserver.OnGlobalLayoutListener() {
                    @Override
                    public void onGlobalLayout() {
                        // 移除监听器，避免重复执行
                        binding.recyclerview.getViewTreeObserver().removeOnGlobalLayoutListener(this);

                        int recyclerViewWidth = binding.recyclerview.getWidth();
                        if (recyclerViewWidth > 0) {
                            // 设置容器宽度
                            keyboardAdapter.setContainerWidth(recyclerViewWidth);

                            // 现在设置数据
                            keyboardAdapter.setData(firstCategoryKeyboards);
                        }
                    }
                }
        );
    }

    private void setupNavigationSidebar() {
        // 初始化侧边栏分类适配器
        navAdapter = new NavCategoryAdapter(this, categoryList);
        navAdapter.setCategoryClickListener(new NavCategoryAdapter.CategoryClickListener() {
            @Override
            public void onCategoryClick(String categoryName, List<DetailsjavaBean> keyboards) {
                // 更新主内容区域显示选中的分类
                updateMainContent(keyboards);
            }
        });

        // 设置侧边栏RecyclerView
        LinearLayoutManager navLayoutManager = new LinearLayoutManager(this);
        binding.navRecyclerview.setLayoutManager(navLayoutManager);
        binding.navRecyclerview.setAdapter(navAdapter);
    }

    private void updateMainContent(List<DetailsjavaBean> keyboards) {
        firstCategoryKeyboards = keyboards;

        // 更新键盘壁纸列表
        keyboardAdapter.setData(keyboards);
        keyboardAdapter.notifyDataSetChanged();

        // 滚动到顶部
        binding.recyclerview.smoothScrollToPosition(0);
    }

    private void setupClickListeners() {
        // 应用图标点击事件 - 跳转到SettingDialog（保持原样）
        binding.appIcon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openSettingDialog();
            }
        });

        // 收藏图标点击事件 - 跳转到CollectionActivity
        binding.collectionIcon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openCollectionActivity();
            }
        });

        // 回到顶部按钮点击事件
        binding.btnScrollToTop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                scrollToTop();
            }
        });
    }

    private void openSettingDialog() {
        try {
            Intent intent = new Intent(this, SettingsActivity.class);
            startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void openCollectionActivity() {
        try {
            Intent intent = new Intent(this, CollectionActivity.class);
            startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void setupScrollListener() {
        binding.recyclerview.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

                boolean canScrollUp = recyclerView.canScrollVertically(-1);
                binding.btnScrollToTop.setVisibility(canScrollUp ? View.VISIBLE : View.GONE);
            }

            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);

                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    boolean canScrollUp = recyclerView.canScrollVertically(-1);
                    binding.btnScrollToTop.setVisibility(canScrollUp ? View.VISIBLE : View.GONE);
                }
            }
        });

        binding.recyclerview.post(new Runnable() {
            @Override
            public void run() {
                boolean canScrollUp = binding.recyclerview.canScrollVertically(-1);
                binding.btnScrollToTop.setVisibility(canScrollUp ? View.VISIBLE : View.GONE);
            }
        });
    }

    private void scrollToTop() {
        if (binding.recyclerview.getLayoutManager() != null) {
            binding.recyclerview.smoothScrollToPosition(0);
        }
    }

    // dp转px的辅助方法
    private int dpToPx(int dp) {
        return (int) (dp * getResources().getDisplayMetrics().density);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        binding = null;
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 从CollectionActivity返回时，可以在这里更新数据（如果需要）
        // 例如刷新收藏状态等
    }
}