package com.snap.wall.activity;

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

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

import com.snap.wall.R;
import com.snap.wall.databinding.ActivityPrimaryBinding;
import com.snap.wall.fragment.FragmentPrefer;
import com.snap.wall.fragment.FragmentPrimary;
import com.snap.wall.fragment.FragmentSetting;
import com.snap.wall.mytool.Comutils;

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

public class PrimaryActivity extends AppCompatActivity implements View.OnClickListener {

    private ActivityPrimaryBinding vb;
    private static final int[] TAB_TITLES = {R.string.home_name, R.string.collections, R.string.setting};
    private int currentTabPosition = 0;
    private static final int HOME_TAB_POSITION = 0;

    private TextView tabHome;
    private TextView tabLike;
    private TextView tabSetting;
    private List<TextView> tabList = new ArrayList<>();
    private List<Fragment> fragmentList = new ArrayList<>();
    // 修复4：保存ViewPager2回调对象，用于注销
    private ViewPager2.OnPageChangeCallback pageChangeCallback;

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

        initFragments();
        initTabViews();
        initViewPager2();
        initSearchClickListener();
        updateTabState(currentTabPosition);
        updateTitle(currentTabPosition);
        updateSearchVisibility(currentTabPosition);
    }
    private void initFragments() {
        fragmentList.add(FragmentPrimary.newInstance(0)); // 首页保留newInstance（需传递参数）
        fragmentList.add(new FragmentPrefer()); // 直接创建实例
        fragmentList.add(new FragmentSetting()); // 直接创建实例
    }

    private void initTabViews() {
        tabHome = findViewById(R.id.tab_home);
        tabLike = findViewById(R.id.tab_like);
        tabSetting = findViewById(R.id.tab_setting);

        tabList.add(tabHome);
        tabList.add(tabLike);
        tabList.add(tabSetting);

        for (int i = 0; i < tabList.size(); i++) {
            TextView tab = tabList.get(i);
            tab.setText(TAB_TITLES[i]);
            tab.setOnClickListener(this);
        }
    }

    private void initViewPager2() {
        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(true);
        vb.viewpager2.setOffscreenPageLimit(2);

        // 修复4：创建并保存回调对象
        pageChangeCallback = new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                currentTabPosition = position;
                updateTabState(position);
                updateTitle(position);
                updateSearchVisibility(position);
            }
        };
        vb.viewpager2.registerOnPageChangeCallback(pageChangeCallback);
    }

    /**
     * 优化2：修改未选中Tab文字颜色，提高可读性
     */
    private void updateTabState(int selectedPosition) {
        for (int i = 0; i < tabList.size(); i++) {
            TextView tab = tabList.get(i);
            boolean isSelected = (i == selectedPosition);

            if (isSelected) {
                tab.setBackgroundResource(R.drawable.tab_selected_bg1);
                tab.setTextColor(getResources().getColor(R.color.white));
            } else {
                tab.setBackgroundResource(R.drawable.bg_purple_round);
                tab.setTextColor(getResources().getColor(R.color.sub_title_color));
            }
        }
    }

    private void updateTitle(int position) {
        if (position < TAB_TITLES.length) {
            String title = getString(TAB_TITLES[position]);
            vb.textviewWallpaper.setText(title);
        }
    }

    private void updateSearchVisibility(int currentPosition) {
        if (currentPosition == HOME_TAB_POSITION) {
            vb.imSearch.setVisibility(View.VISIBLE);
        } else {
            vb.imSearch.setVisibility(View.GONE);
        }
    }

    private void initSearchClickListener() {
        vb.imSearch.setOnClickListener(v -> {
            Intent intent = new Intent(PrimaryActivity.this, MySearchActivity.class);
            startActivity(intent);
        });
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.tab_home) {
            currentTabPosition = 0;
            vb.viewpager2.setCurrentItem(0, true);
        } else if (id == R.id.tab_like) {
            currentTabPosition = 1;
            vb.viewpager2.setCurrentItem(1, true);
        } else if (id == R.id.tab_setting) {
            currentTabPosition = 2;
            vb.viewpager2.setCurrentItem(2, true);
        }
        updateTabState(currentTabPosition);
        updateTitle(currentTabPosition);
        updateSearchVisibility(currentTabPosition);
    }

    /**
     * 修复4：注销保存的回调对象，避免内存泄漏
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        vb.viewpager2.unregisterOnPageChangeCallback(pageChangeCallback);
        vb = null;
    }

    public void switchToPreviousFragment() {
        if (currentTabPosition > 0) {
            currentTabPosition--;
            vb.viewpager2.setCurrentItem(currentTabPosition, true);
        } else {
            // 如需退出App，取消注释下面一行
            // finish();
        }
    }
}