package com.lock.arcanvasart.fragment;

import android.os.Bundle;
import android.os.Handler;
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 androidx.fragment.app.Fragment;
import androidx.lifecycle.LiveData;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.viewpager2.widget.ViewPager2;

import com.lock.arcanvasart.R;
import com.lock.arcanvasart.Utils.ItemDecoration;
import com.lock.arcanvasart.adapter.CategoryAdapter;
import com.lock.arcanvasart.adapter.MainAdapter;
import com.lock.arcanvasart.databinding.FragmentMainBinding;
import com.lock.arcanvasart.room.AppDatabase;
import com.lock.arcanvasart.room.FavoriteImage;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Random;

public class MainFragment extends Fragment {

    private FragmentMainBinding binding;
    private CategoryAdapter imageAdapter;
    private final List<FavoriteImage> images = new ArrayList<>();
    private Handler handler;
    private AppDatabase appDatabase;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = FragmentMainBinding.inflate(inflater, container, false);
        appDatabase = AppDatabase.getInstance(getContext());

        // 设置 RecyclerView
        setupRecyclerView();

        // 加载并观察数据
        loadImagesForCarousel();

        loadImagesForRecyclerView();

        return binding.getRoot();
    }

    private void setupRecyclerView() {
        imageAdapter = new CategoryAdapter(getContext(), images);
        binding.recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 2));
        binding.recyclerView.setAdapter(imageAdapter);

        ItemDecoration itemDecoration = new ItemDecoration(12, 10, 9);
        binding.recyclerView.addItemDecoration(itemDecoration);
    }

    private void loadImagesForRecyclerView() {

        int randomLimit = new Random().nextInt(321) + 20;

        LiveData<List<FavoriteImage>> recyclerImagesLiveData = appDatabase.favoriteImageDao().getImagesForRecyclerView(randomLimit, randomLimit-20);

        // 观察 LiveData 的变化
        recyclerImagesLiveData.observe(getViewLifecycleOwner(), recyclerImages -> {
            if (recyclerImages != null) {
                images.clear();
                images.addAll(recyclerImages);
                imageAdapter.notifyDataSetChanged();  // 刷新 RecyclerView
            }
        });
    }

    private void loadImagesForCarousel() {
        new Thread(() -> {
            List<FavoriteImage> carouselImages = AppDatabase
                    .getInstance(getContext())
                    .favoriteImageDao()
                    .getRandomImagesForCarousel();

            requireActivity().runOnUiThread(() -> {
                MainAdapter adapter = new MainAdapter(getContext(), carouselImages);
                binding.viewPager.setAdapter(adapter);
                setupIndicators(carouselImages.size());

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

                // 设置轮播图的监听器
                setupViewPagerListener();

                // 在数据加载完毕后再开始自动滚动
                autoScrollViewPager();  // 确保自动滚动在数据加载后开始

            });
        }).start();
    }


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

                updateIndicators(position); // 更新圆点

            }
        });

    }

    private void autoScrollViewPager() {
        final int delay = 3000;  // 设置轮播间隔时间（毫秒）
        final int period = 3000;  // 设置轮播间隔时间（毫秒）

        // 使用 Handler 来实现定时任务
        handler = new Handler();
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                // 获取当前页面的位置
                int currentItem = binding.viewPager.getCurrentItem();

                // 切换到下一个页面
                int nextItem = currentItem + 1;
                if (nextItem >= Objects.requireNonNull(binding.viewPager.getAdapter()).getItemCount()) {
                    nextItem = 0;  // 如果已经到最后一页，则回到第一页
                }

                binding.viewPager.setCurrentItem(nextItem, true); // 平滑切换

                // 每隔一定时间执行一次，达到自动切换的效果
                handler.postDelayed(this, period);
            }
        };

        // 延迟执行第一次轮播
        handler.postDelayed(runnable, delay);
    }

    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 onDestroyView() {
        super.onDestroyView();
        if (handler != null) {
            handler.removeCallbacksAndMessages(null); // 移除所有回调
        }
        binding = null;
    }
}
