package com.key.vibekeyboard.ui.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.data.database.entity.WallpaperInfo;
import com.key.vibekeyboard.ui.activity.CategoryActivity;
import com.key.vibekeyboard.ui.activity.SearchActivity;
import com.key.vibekeyboard.ui.adapter.HomeSliderAdapter;
import com.key.vibekeyboard.R;
import com.key.vibekeyboard.data.bean.Category;
import com.key.vibekeyboard.ui.adapter.WallpaperAdapter;
import com.key.vibekeyboard.utils.ItemDecoration;
import com.key.vibekeyboard.utils.JsonUtils;
import com.key.vibekeyboard.databinding.FragmentHomeBinding;
import com.key.vibekeyboard.topon.AdManager;
import com.key.vibekeyboard.topon.onActionListener;

import java.util.List;
import java.util.Random;


public class HomeFragment extends Fragment {

    private FragmentHomeBinding binding;
    private HomeSliderAdapter homeSliderAdapter;
    private List<Category> categories;

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

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

        AdManager.loadAllAd();

        initData();
        initEvent();

        return binding.getRoot();

    }

    public void initData() {
        categories = JsonUtils.parseJson("keyboard.json");
        Log.d("dsd", "size" + categories.size());

        homeSliderAdapter = new HomeSliderAdapter(requireContext(), categories);
        binding.homeViewPager.setAdapter(homeSliderAdapter);
        setupIndicators(categories.size());

        Random random = new Random();
        int randomIndex = random.nextInt(categories.size());
        List<WallpaperInfo> wallpaperInfos = categories.get(randomIndex).getList();

        binding.homeRecycler.setLayoutManager(new GridLayoutManager(getContext(), 2));
        WallpaperAdapter homeRecyclerViewAdapter = new WallpaperAdapter(requireContext(), wallpaperInfos);
        binding.homeRecycler.setAdapter(homeRecyclerViewAdapter);

        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) {
                AdManager.showTopOn(requireActivity(), new onActionListener() {
                    @Override
                    public void onAction() {
                        Intent intent = new Intent(getContext(), CategoryActivity.class);
                        startActivity(intent);
                    }
                });
            }
        });

        binding.homeViewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                if (position == homeSliderAdapter.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;
        binding.homeViewPager.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (binding == null) {
                    return;
                }

                int currentItem = binding.homeViewPager.getCurrentItem();
                int nextItem = currentItem + 1;

                if (nextItem >= homeSliderAdapter.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();
        if (binding != null) {
            binding.homeViewPager.removeCallbacks(null);
        }
        binding = null;
    }

}