package com.key.vibekeyboard.Fragment;

import android.content.Intent;
import android.os.Bundle;

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

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.key.vibekeyboard.Activity.CategoryActivity;
import com.key.vibekeyboard.Activity.SearchActivity;
import com.key.vibekeyboard.Adapter.HomeRecyclerViewAdapter;
import com.key.vibekeyboard.Adapter.HomeViewPager2Adapter;
import com.key.vibekeyboard.R;
import com.key.vibekeyboard.Room.Category;
import com.key.vibekeyboard.Utils.ItemDecoration;
import com.key.vibekeyboard.Utils.Mytool;
import com.key.vibekeyboard.databinding.FragmentHomeBinding;

import java.util.List;


public class HomeFragment extends Fragment {

    private FragmentHomeBinding binding;
    private HomeViewPager2Adapter homeViewPager2Adapter;
    private List<Category> categories;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        binding = FragmentHomeBinding.inflate(inflater, container, false);

        initData();
        initEvent();

        return binding.getRoot();

    }

    public void initData() {
        // 解析Json
        categories = Mytool.parseJsonToList("keyboard.json");
        Log.d("dsd", "size" + categories.size());

        // 设置ViewPager2
        homeViewPager2Adapter = new HomeViewPager2Adapter(requireContext(), categories);
        binding.homeViewPager.setAdapter(homeViewPager2Adapter);
        setupIndicators(categories.size());

        // 设置RecyclerView
        binding.homeRecycler.setLayoutManager(new GridLayoutManager(getContext(), 2));
        HomeRecyclerViewAdapter homeRecyclerViewAdapter = new HomeRecyclerViewAdapter(requireContext(), categories);
        binding.homeRecycler.setAdapter(homeRecyclerViewAdapter);

        // 为 RecyclerView 添加自定义的间距装饰。
        ItemDecoration itemDecoration = new ItemDecoration(16, 19, 10);
        binding.homeRecycler.addItemDecoration(itemDecoration);

    }

    public void initEvent() {

        binding.homeAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), CategoryActivity.class);
                startActivity(intent);
            }
        });

        binding.homeViewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                if (position == homeViewPager2Adapter.getItemCount() - 1) {
                    // 如果用户手动滑到了最后的虚拟页面，切换回第一张
                    binding.homeViewPager.postDelayed(() -> binding.homeViewPager.setCurrentItem(0, false), 300);
                }
            }
        });

        binding.homeSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), SearchActivity.class);
                startActivity(intent);
            }
        });

        binding.homeViewPager.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                // 移除布局监听器，避免重复执行
                binding.homeViewPager.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                // 动态生成圆点指示器
                setupIndicators(categories.size());
                // 初始设置选中的圆点
                updateIndicators(0);
            }
        });

        // 设置自动轮播功能
        autoSlideImages();

        setupViewPagerListener();
    }

    // 自动轮播图片
    private void autoSlideImages() {
        final int delay = 3000; // 延迟 3 秒
        binding.homeViewPager.postDelayed(new Runnable() {
            @Override
            public void run() {
                int currentItem = binding.homeViewPager.getCurrentItem();
                int nextItem = currentItem + 1;

                if (nextItem >= homeViewPager2Adapter.getItemCount()) {
                    // 如果到达了最后的虚拟页面，瞬间跳回第一张，禁用动画
                    binding.homeViewPager.setCurrentItem(0, false);
                } else {
                    // 正常切换到下一张，有动画效果
                    binding.homeViewPager.setCurrentItem(nextItem, true);
                }

                // 继续下一次轮播
                binding.homeViewPager.postDelayed(this, delay);
            }
        }, delay);
    }

    private void setupViewPagerListener() {
        binding.homeViewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);

                updateIndicators(position); // 更新圆点

            }
        });

    }

    private void setupIndicators(int count) {
        LinearLayout indicatorLayout = binding.indicatorLayout;
        indicatorLayout.removeAllViews(); // 清空原有的圆点

        for (int i = 0; i < count; i++) {
            ImageView indicator = new ImageView(getContext());
            indicator.setImageResource(R.drawable.circle_indicator); // 默认圆点
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            params.setMargins(8, 0, 8, 0); // 设置圆点间距
            indicator.setLayoutParams(params);
            indicatorLayout.addView(indicator);
        }

        // 延迟设置选中的圆点
        indicatorLayout.post(() -> updateIndicators(0)); // 设置第一个圆点为选中状态
    }

    private void updateIndicators(int position) {
        LinearLayout indicatorLayout = binding.indicatorLayout;
        int childCount = indicatorLayout.getChildCount();

        for (int i = 0; i < childCount; i++) {
            ImageView indicator = (ImageView) indicatorLayout.getChildAt(i);
            if (i == position) {
                indicator.setImageResource(R.drawable.circle_indicator_selected); // 当前页选中的圆点
            } else {
                indicator.setImageResource(R.drawable.circle_indicator); // 默认圆点
            }
        }

        // 强制更新布局，确保圆点大小正确
        indicatorLayout.requestLayout();
    }

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

}