package com.idle.wall.idlefragment;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import com.idle.wall.IdleApp;
import com.idle.wall.R;
import com.idle.wall.databinding.FragmentIdleMainBinding;
import com.idle.wall.idleactivity.IdleListActivity;
import com.idle.wall.idletool.Comutils;

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

public class FragmentIdleMain extends Fragment {
    private FragmentIdleMainBinding vb;
    private ProgressBar loadingPb;
    private LinearLayout tabContainer;
    private ViewPager2 contentViewPager;
    private List<String> categoryNames = new ArrayList<>();
    private int currentSelectedPos = 0;
    private List<TextView> tabViewList = new ArrayList<>();

    public static FragmentIdleMain newInstance(int type) {
        FragmentIdleMain fragment = new FragmentIdleMain();
        Bundle bundle = new Bundle();
        bundle.putInt(Comutils.key_index, type);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        vb = FragmentIdleMainBinding.inflate(inflater, container, false);
        loadingPb = vb.loadingPb;
        tabContainer = vb.tabContainer;
        contentViewPager = vb.contentViewPager;
        return vb.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        // 初始化分类数据（同步从App获取）
        categoryNames = IdleApp.getCategoryNames();
        initContentViewPager();
        initCategoryData();
        setupViewPagerListener();
    }

    private void initContentViewPager() {
        contentViewPager.setAdapter(new FragmentStateAdapter(this) {
            @NonNull
            @Override
            public Fragment createFragment(int position) {
                FragmentIdlePage fragment = new FragmentIdlePage();
                Bundle bundle = new Bundle();
                String cateName = (position < categoryNames.size()) ? categoryNames.get(position) : "";
                bundle.putString(IdleListActivity.key_index, cateName);
                fragment.setArguments(bundle);
                return fragment;
            }

            @Override
            public int getItemCount() {
                return categoryNames.size();
            }
        });
        contentViewPager.setOffscreenPageLimit(2);
        contentViewPager.setUserInputEnabled(true);
    }

    private void initCategoryData() {
        loadingPb.setVisibility(View.VISIBLE);
        tabContainer.removeAllViews();
        tabViewList.clear();

        // 同步创建Tab（主线程）
        createTabViews();

        loadingPb.setVisibility(View.GONE);
        updateTabSelection(currentSelectedPos);
        contentViewPager.setCurrentItem(currentSelectedPos, false);
    }

    private void createTabViews() {
        if (categoryNames.isEmpty() || getContext() == null) return;

        Context context = getContext();
        LinearLayout.LayoutParams tabParams = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.MATCH_PARENT
        );
        int marginRight = Comutils.dp2px(context, 8);
        int marginLeft = Comutils.dp2px(context, 8);
        tabParams.setMargins(marginLeft, 0, marginRight, 0);

        for (int i = 0; i < categoryNames.size(); i++) {
            String categoryName = categoryNames.get(i);
            TextView tabView = new TextView(context);

            tabView.setText(categoryName);
            tabView.setTextSize(14);
            tabView.setPadding(
                    Comutils.dp2px(context, 12),
                    Comutils.dp2px(context, 8),
                    Comutils.dp2px(context, 12),
                    Comutils.dp2px(context, 8)
            );
            tabView.setLayoutParams(tabParams);
            tabView.setClickable(true);
            tabView.setFocusable(true);

            tabView.setTag(i);

            tabView.setOnClickListener(v -> {
                int position = (int) v.getTag();
                if (currentSelectedPos != position) {
                    currentSelectedPos = position;
                    updateTabSelection(position);
                    contentViewPager.setCurrentItem(position, true);
                }
            });

            tabContainer.addView(tabView);
            tabViewList.add(tabView);
        }
    }

    private void updateTabSelection(int selectedPosition) {
        if (tabViewList.isEmpty() || selectedPosition >= tabViewList.size()) return;

        for (int i = 0; i < tabViewList.size(); i++) {
            TextView tabView = tabViewList.get(i);
            if (i == selectedPosition) {
                tabView.setTextColor(getResources().getColor(R.color.white));
                tabView.setBackgroundResource(R.drawable.tab_selected_bg1);
            } else {
                tabView.setTextColor(getResources().getColor(R.color.sub_title_color));
                tabView.setBackgroundResource(R.drawable.bg_idle_round);
            }
        }
    }

    private void setupViewPagerListener() {
        contentViewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                if (currentSelectedPos != position) {
                    currentSelectedPos = position;
                    updateTabSelection(position);
                    scrollToSelectedTab(position);
                }
            }
        });
    }

    private void scrollToSelectedTab(int position) {
        if (position < tabViewList.size()) {
            TextView selectedTab = tabViewList.get(position);
            tabContainer.scrollTo(selectedTab.getLeft() - Comutils.dp2px(getContext(), 8), 0);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (contentViewPager != null) {
            contentViewPager.unregisterOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {});
        }
        tabViewList.clear();
        vb = null;
        loadingPb = null;
        tabContainer = null;
        contentViewPager = null;
    }
}