package com.wall.proshot.wallpapers.myacctivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import com.wall.proshot.wallpapers.myfragment.FragmentLike;
import com.wall.proshot.wallpapers.myfragment.FragmentMain;
import com.wall.proshot.wallpapers.mytool.MyComUtils;
import com.wall.proshot.wallpapers.R;
import com.wall.proshot.wallpapers.databinding.ActivityMyMainBinding;
import com.wall.proshot.wallpapers.databinding.MyItemTabBinding;

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


public class MyMainActivity extends AppCompatActivity {

    private ActivityMyMainBinding vb;
    private List<Fragment> fragmentList = new ArrayList<>();
    // Tab 图标选择器（主页：home_0选中 / home_1未选中；收藏：对应选中/未选中图）
    private int[] tabIcons = {
            R.drawable.selector_tab_home,
            R.drawable.selector_tab_like
    };
    private String[] tabTitles;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        vb = ActivityMyMainBinding.inflate(getLayoutInflater());
        MyComUtils.initFull(this, false);
        setContentView(vb.getRoot());

        // 初始化顶部标题
        tabTitles = new String[]{
                getString(R.string.app_name),
                getString(R.string.collections)
        };

        // 初始化 Fragment 列表
        initFragments();
        // 修复 Tab 初始选中状态逻辑
        initViewPagerAndTab();
        // 初始化点击事件
        initClickEvents();
    }

    private void initFragments() {
        fragmentList.clear();
        fragmentList.add(FragmentMain.newInstance(0));
        fragmentList.add(FragmentLike.newInstance());
    }

    private void initViewPagerAndTab() {
        // ViewPager2 适配器
        vb.viewpager2.setAdapter(new FragmentStateAdapter(this) {
            @NonNull
            @Override
            public Fragment createFragment(int position) {
                return fragmentList.get(position);
            }

            @Override
            public int getItemCount() {
                return fragmentList.size();
            }
        });

        vb.viewpager2.setUserInputEnabled(false);

        // 绑定 TabLayout 和 ViewPager2
        new TabLayoutMediator(vb.tab, vb.viewpager2, new TabLayoutMediator.TabConfigurationStrategy() {
            @Override
            public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
                MyItemTabBinding tabBinding = MyItemTabBinding.inflate(getLayoutInflater());
                // 设置 Tab 图标（选择器自动处理选中/未选中状态）
                tabBinding.imageIcon.setImageDrawable(ContextCompat.getDrawable(
                        MyMainActivity.this, tabIcons[position]
                ));
                // 初始状态：第 0 个 Tab（主页）显示指示器（无需 setSelected）
                tabBinding.imageIndicator.setVisibility(position == 0 ? View.VISIBLE : View.GONE);
                tab.setCustomView(tabBinding.getRoot());
            }
        }).attach();

        if (vb.tab.getTabCount() > 0) {
            vb.tab.selectTab(vb.tab.getTabAt(0));
            // 同步顶部标题
            vb.textviewWallpaper.setText(tabTitles[0]);
        }

        // Tab 选中状态监听
        vb.tab.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                View customView = tab.getCustomView();
                if (customView != null) {
                    // 显示选中指示器
                    View indicator = customView.findViewById(R.id.image_indicator);
                    indicator.setVisibility(View.VISIBLE);
                    // 触发图标选择器切换到选中状态（通过设置 ImageView 的 selected 属性）
                    ImageView icon = customView.findViewById(R.id.image_icon);
                    icon.setSelected(true);
                }
                // 同步 ViewPager2 页面
                int position = tab.getPosition();
                vb.viewpager2.setCurrentItem(position, false);
                // 更新顶部标题
                vb.textviewWallpaper.setText(tabTitles[position]);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                View customView = tab.getCustomView();
                if (customView != null) {
                    // 隐藏选中指示器
                    View indicator = customView.findViewById(R.id.image_indicator);
                    indicator.setVisibility(View.INVISIBLE);
                    // 触发图标选择器切换到未选中状态
                    ImageView icon = customView.findViewById(R.id.image_icon);
                    icon.setSelected(false);
                }
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
                // 重选 Tab 滚动到顶部（可选）
                int position = tab.getPosition();
                if (position == 0) {
                    FragmentMain homeFragment = (FragmentMain) fragmentList.get(0);
                    homeFragment.scrollToTop();
                } else if (position == 1) {
                    FragmentLike likeFragment = (FragmentLike) fragmentList.get(1);
                    likeFragment.scrollToTop();
                }
            }
        });

        // ViewPager2 页面切换监听（防止状态不同步）
        vb.viewpager2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                TabLayout.Tab tab = vb.tab.getTabAt(position);
                if (tab != null && !tab.isSelected()) {
                    vb.tab.selectTab(tab);
                }
            }
        });
    }

    private void initClickEvents() {
        // 搜索图标点击
        vb.imSearch.setOnClickListener(v -> {
            Intent intent = new Intent(MyMainActivity.this, SearchActivity.class);
            startActivity(intent);
        });

        // 设置图标点击
        vb.imSetting.setOnClickListener(v -> {
            Intent intent = new Intent(MyMainActivity.this, MySettingActivity.class);
            startActivity(intent);
        });
    }

}