package com.example.wallisyn.Activity;

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

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.adapter.FragmentStateAdapter;

import com.example.wallisyn.ad.AdsInsUtil;
import com.example.wallisyn.ad.LoadListener;
import com.google.android.material.tabs.TabLayout;
import com.example.wallisyn.R;
import com.example.wallisyn.databinding.ActivityHomeMainBinding;
import com.example.wallisyn.databinding.ItemBottomTabBinding;
import com.example.wallisyn.fragment.WallpaperLikeFragment;
import com.example.wallisyn.fragment.HomeMainFragment;
import com.example.wallisyn.fragment.AppSettingsFragment;
import com.example.wallisyn.tool.ComUtils;
import com.thinkup.core.api.TUAdInfo;

import org.jetbrains.annotations.NotNull;

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

public class HomeMainActivity extends AppCompatActivity {
    private static final String TAG = "HomeMainActivity";
    private ActivityHomeMainBinding vb;

    private int[] tabIcons = {
            R.drawable.home,
            R.drawable.collections,
            R.drawable.settings
    };

    private int tabSelectedColor;
    private int tabUnselectedColor;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        loadAd();
        try {
            // 1. 全屏初始化：添加这行代码（根据需求选择true=黑色背景，false=白色背景）
            ComUtils.initFull(this, false); // 这里用false=白色背景，可根据需要修改

            // 2. 加载布局（必须在全屏初始化之后，避免布局被状态栏遮挡）
            vb = ActivityHomeMainBinding.inflate(getLayoutInflater());
            setContentView(vb.getRoot());

            // 修复：替换弃用的系统颜色为自定义颜色或通用系统颜色
            tabSelectedColor = getSafeColor(R.color.tab_selected, R.color.pink); // 改用自定义pink
            tabUnselectedColor = getSafeColor(R.color.tab_unselected, android.R.color.darker_gray);

            // 初始化Fragment列表（强制非空）
            List<Fragment> fragmentList = new ArrayList<>();
            fragmentList.add(new HomeMainFragment());
            fragmentList.add(new WallpaperLikeFragment());
            fragmentList.add(new AppSettingsFragment());

            // 初始化ViewPager2（绑定生命周期）
            vb.viewpager2.setAdapter(new FragmentStateAdapter(getSupportFragmentManager(), getLifecycle()) {
                @NonNull
                @Override
                public Fragment createFragment(int position) {
                    return fragmentList.get(position);
                }

                @Override
                public int getItemCount() {
                    return fragmentList.size();
                }
            });
            vb.viewpager2.setUserInputEnabled(false);

            // 初始化Tab（容错处理）
            initTabs(fragmentList.size());

            // 初始化Tab监听
            initTabListener();

            // 初始化搜索按钮（空安全）
            if (vb.imSearch != null) {
                vb.imSearch.setOnClickListener(v -> {
                    try {
                        Intent intent = new Intent(HomeMainActivity.this, WallpaperSearchActivity.class);
                        if (intent.resolveActivity(getPackageManager()) != null) {
                            startActivity(intent);
                        } else {
                            Toast.makeText(this, "搜索页面未找到", Toast.LENGTH_SHORT).show();
                        }
                    } catch (Exception e) {
                        Log.e(TAG, "搜索跳转失败", e);
                    }
                });
            }

        } catch (Exception e) {
            Log.e(TAG, "初始化崩溃", e);
            Toast.makeText(this, "首页加载失败", Toast.LENGTH_SHORT).show();
            finish();
        }
    }

    // 修复：Android 6.0+ 适配 ContextCompat.getColor（原代码无问题，保留并优化注释）
    private int getSafeColor(int resId, int defaultResId) {
        try {
            return ContextCompat.getColor(this, resId);
        } catch (Exception e) {
            Log.w(TAG, "获取颜色失败，使用默认颜色", e);
            return ContextCompat.getColor(this, defaultResId);
        }
    }

    private void initTabs(int tabCount) {
        for (int i = 0; i < tabCount; i++) {
            TabLayout.Tab tab = vb.tab.newTab();
            try {
                ItemBottomTabBinding tabVb = ItemBottomTabBinding.inflate(getLayoutInflater());
                if (i < tabIcons.length && tabIcons[i] != 0) {
                    tabVb.imageIcon.setImageDrawable(ContextCompat.getDrawable(this, tabIcons[i]));
                    tabVb.imageIcon.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
                    // 适配全屏背景：如果背景是黑色，可调整图标颜色避免看不见
                    tabVb.imageIcon.setColorFilter(i == 0 ? tabSelectedColor : tabUnselectedColor);
                } else {
                    tabVb.imageIcon.setVisibility(View.GONE);
                }
                tabVb.imageIndicator.setVisibility(i == 0 ? View.VISIBLE : View.GONE);
                tab.setCustomView(tabVb.getRoot());
            } catch (Exception e) {
                Log.w(TAG, "创建自定义Tab失败，使用文字Tab", e);
                tab.setText(i == 0 ? "首页" : i == 1 ? "收藏" : "设置");
            }
            vb.tab.addTab(tab);
        }
    }

    private void initTabListener() {
        vb.tab.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                vb.viewpager2.setCurrentItem(tab.getPosition(), false);
                View customView = tab.getCustomView();
                if (customView != null) {
                    ImageView icon = customView.findViewById(R.id.image_icon);
                    if (icon != null) icon.setColorFilter(tabSelectedColor);
                    View indicator = customView.findViewById(R.id.image_indicator);
                    if (indicator != null) indicator.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                View customView = tab.getCustomView();
                if (customView != null) {
                    ImageView icon = customView.findViewById(R.id.image_icon);
                    if (icon != null) icon.setColorFilter(tabUnselectedColor);
                    View indicator = customView.findViewById(R.id.image_indicator);
                    if (indicator != null) indicator.setVisibility(View.GONE);
                }
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
        });
    }

    // 可选：重写onWindowFocusChanged，确保切换页面后仍保持全屏
    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            ComUtils.initFull(this, false); // 与onCreate中保持一致的背景色
        }
    }

    private void loadAd() {
        AdsInsUtil.INSTANCE.loadAd(this, AdsInsUtil.Placement.TOP_ON_AD_ONE, new LoadListener() {
            @Override
            public void loaded(@NotNull TUAdInfo ad) {

            }

            @Override
            public void loadFailed(@NotNull String error) {

            }
        });
        AdsInsUtil.INSTANCE.loadAd(this, AdsInsUtil.Placement.TOP_ON_AD_TOW, new LoadListener() {
            @Override
            public void loaded(@NotNull TUAdInfo ad) {

            }

            @Override
            public void loadFailed(@NotNull String error) {

            }
        });
    }
}