package com.wall.dream.wallpapers.acacctivity;

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

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.google.android.material.tabs.TabLayout;
import com.tradplus.ads.base.bean.TPAdInfo;
import com.wall.dream.wallpapers.R;
import com.wall.dream.wallpapers.ad.AdsInsUtil;
import com.wall.dream.wallpapers.ad.LoadListener;
import com.wall.dream.wallpapers.databinding.ViewMainBinding;
import com.wall.dream.wallpapers.databinding.PagTabBinding;
import com.wall.dream.wallpapers.View.ViewFeatured;
import com.wall.dream.wallpapers.View.ViewLike;
import com.wall.dream.wallpapers.View.ViewMain;
import com.wall.dream.wallpapers.View.ViewSettings;
import com.wall.dream.wallpapers.GJ.ComUtilsGJ;

import org.jetbrains.annotations.NotNull;

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

public class MainViewActivity extends AppCompatActivity {


    private ViewMainBinding vb;
    private List<Fragment> topFragments = new ArrayList<>();
    private Fragment currentTopFragment;
    private List<Fragment> bottomFragments = new ArrayList<>();
    private Fragment currentBottomFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        vb = ViewMainBinding.inflate(getLayoutInflater());
        ComUtilsGJ.initFull(this, false);
        setContentView(vb.getRoot());
        
        // 初始化顶部Tab（精选/收藏）
        initTopTabs();
        
        // 初始化底部导航（首页/分类/设置）
        initBottomTabs();
        
        // 确保初始状态：显示顶部导航栏和搜索按钮（默认显示首页）
        vb.topBar.setVisibility(View.VISIBLE);
        vb.imSearch.setVisibility(View.VISIBLE);
    }

    @SuppressLint("SetTextI18n")
    private void initTopTabs() {
        // 顶部Fragment列表
        Fragment featuredFragment = ViewFeatured.newInstance(); // 精选
        Fragment likeFragment = ViewLike.newInstance();         // 收藏
        topFragments.add(featuredFragment);
        topFragments.add(likeFragment);

        // 使用FragmentManager添加Fragment（不使用ViewPager2）
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        
        // 添加所有Fragment，默认显示第一个
        for (int i = 0; i < topFragments.size(); i++) {
            Fragment fragment = topFragments.get(i);
            String tag = "top_fragment_" + i;
            transaction.add(R.id.top_content_container, fragment, tag);
            if (i != 0) {
                transaction.hide(fragment);
            } else {
                currentTopFragment = fragment;
            }
        }
        transaction.commit();

        // 设置顶部TabLayout - 参考图片4D LIVE 4K风格（英文）
        // 创建自定义Tab视图
        for (int i = 0; i < 2; i++) {
            TabLayout.Tab tab = vb.topTab.newTab();
            View customView = getLayoutInflater().inflate(R.layout.pag_top_tab, null);
            android.widget.TextView mainText = customView.findViewById(R.id.tab_main_text);
            android.widget.TextView subText = customView.findViewById(R.id.tab_sub_text);
            
            View indicator = customView.findViewById(R.id.tab_indicator);
            
            if (i == 0) {
                // 第一个Tab：FEATURED（类似4D风格）- 白色加粗，突出显示 + 显示指示器
                mainText.setText(R.string.featured);
                mainText.setTextSize(26);
                mainText.setTextColor(ContextCompat.getColor(this, R.color.white));
                mainText.setTypeface(null, android.graphics.Typeface.BOLD);
                mainText.setAlpha(1.0f);
                // 显示选中指示器
                if (indicator != null) {
                    indicator.setVisibility(View.VISIBLE);
                }
            } else {
                // 第二个Tab：FAVORITE（类似LIVE/4K风格）- 白色，降低透明度 + 隐藏指示器
                mainText.setText("LIKE");
                mainText.setTextSize(20);
                mainText.setTextColor(ContextCompat.getColor(this, R.color.white));
                mainText.setTypeface(null, android.graphics.Typeface.NORMAL);
                mainText.setAlpha(0.5f);
                // 隐藏选中指示器
                if (indicator != null) {
                    indicator.setVisibility(View.GONE);
                }
            }
            
            tab.setCustomView(customView);
            vb.topTab.addTab(tab);
        }

        // 顶部Tab切换监听 - 使用Fragment show/hide（不使用ViewPager2）
        vb.topTab.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                int position = tab.getPosition();
                switchTopFragment(position);
                
                // 更新选中Tab样式（大字体、粗体、白色，突出显示 + 显示指示器）
                View customView = tab.getCustomView();
                if (customView != null) {
                    android.widget.TextView mainText = customView.findViewById(R.id.tab_main_text);
                    View indicator = customView.findViewById(R.id.tab_indicator);
                    
                    if (mainText != null) {
                        mainText.setTextSize(26);
                        mainText.setTextColor(ContextCompat.getColor(MainViewActivity.this, R.color.white));
                        mainText.setTypeface(null, android.graphics.Typeface.BOLD);
                        mainText.setAlpha(1.0f);
                    }
                    
                    // 显示选中指示器
                    if (indicator != null) {
                        indicator.setVisibility(View.VISIBLE);
                    }
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                // 更新未选中Tab样式（小字体、白色，50%透明度 + 隐藏指示器）
                View customView = tab.getCustomView();
                if (customView != null) {
                    android.widget.TextView mainText = customView.findViewById(R.id.tab_main_text);
                    View indicator = customView.findViewById(R.id.tab_indicator);
                    
                    if (mainText != null) {
                        mainText.setTextSize(20);
                        mainText.setTextColor(ContextCompat.getColor(MainViewActivity.this, R.color.white));
                        mainText.setTypeface(null, android.graphics.Typeface.NORMAL);
                        mainText.setAlpha(0.5f);
                    }
                    
                    // 隐藏选中指示器
                    if (indicator != null) {
                        indicator.setVisibility(View.GONE);
                    }
                }
            }

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

    /**
     * 切换顶部Fragment（使用show/hide，不使用ViewPager2）
     */
    private void switchTopFragment(int position) {
        if (position < 0 || position >= topFragments.size()) {
            return;
        }
        
        Fragment targetFragment = topFragments.get(position);
        if (targetFragment == currentTopFragment) {
            return;
        }
        
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        
        // 隐藏当前Fragment
        if (currentTopFragment != null) {
            transaction.hide(currentTopFragment);
        }
        
        // 显示目标Fragment
        transaction.show(targetFragment);
        transaction.commit();
        
        currentTopFragment = targetFragment;
    }

    /**
     * 切换底部Fragment（使用show/hide，不使用ViewPager2）
     */
    private void switchBottomFragment(int position) {
        if (position < 0 || position >= bottomFragments.size()) {
            return;
        }
        
        Fragment targetFragment = bottomFragments.get(position);
        if (targetFragment == currentBottomFragment) {
            return;
        }
        
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        
        // 隐藏当前Fragment
        if (currentBottomFragment != null) {
            transaction.hide(currentBottomFragment);
        }
        
        // 显示目标Fragment
        transaction.show(targetFragment);
        transaction.commit();
        
        currentBottomFragment = targetFragment;
    }

    private void initBottomTabs() {
        // 底部Fragment列表 - 分类和设置
        Fragment categoryFragment = ViewMain.newInstance(0);     // 分类
        Fragment settingsFragment = ViewSettings.newInstance();  // 设置
        bottomFragments.add(categoryFragment);
        bottomFragments.add(settingsFragment);

        int[] ints = {R.drawable.selector_home, R.drawable.selector_tab_category, R.drawable.selector_settings};
        
        // 使用FragmentManager添加Fragment（不使用ViewPager2）
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        
        // 添加所有Fragment，默认隐藏（因为默认显示首页）
        for (int i = 0; i < bottomFragments.size(); i++) {
            Fragment fragment = bottomFragments.get(i);
            String tag = "bottom_fragment_" + i;
            transaction.add(R.id.bottom_content_container, fragment, tag);
            transaction.hide(fragment);
        }
        transaction.commit();

        // 创建3个底部Tab：首页、分类、设置
        for (int i = 0; i < 3; i++) {
            TabLayout.Tab tab = vb.tab.newTab();
            PagTabBinding tabVb = PagTabBinding.inflate(getLayoutInflater());
            tabVb.imageIcon.setImageDrawable(ContextCompat.getDrawable(this, ints[i]));
            tab.setCustomView(tabVb.getRoot());
            if (i == 0) {
                // 首页初始选中状态
                applySelectedEffect(tabVb);
            } else {
                // 未选中状态
                applyUnselectedEffect(tabVb);
            }
            vb.tab.addTab(tab);
        }
        vb.tab.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                int position = tab.getPosition();
                View customView = tab.getCustomView();
                if (customView == null) return;
                
                PagTabBinding tabVb = PagTabBinding.bind(customView);
                
                // 应用统一的选中效果
                applySelectedEffect(tabVb);
                
                // 显示/隐藏顶部Tab和内容容器
                if (position == 0) {
                    // 首页：显示顶部Tab和内容容器，显示搜索按钮
                    vb.topTab.setVisibility(View.VISIBLE);
                    vb.topContentContainer.setVisibility(View.VISIBLE);
                    vb.bottomContentContainer.setVisibility(View.GONE);
                    vb.topBar.setVisibility(View.VISIBLE);
                    vb.imSearch.setVisibility(View.VISIBLE);
                    
                    // 隐藏所有底部Fragment
                    if (currentBottomFragment != null) {
                        FragmentManager fragmentManager = getSupportFragmentManager();
                        FragmentTransaction transaction = fragmentManager.beginTransaction();
                        transaction.hide(currentBottomFragment);
                        transaction.commit();
                        currentBottomFragment = null;
                    }
                } else {
                    // 分类或设置：显示底部容器，隐藏搜索按钮
                    vb.topTab.setVisibility(View.GONE);
                    vb.topContentContainer.setVisibility(View.GONE);
                    vb.bottomContentContainer.setVisibility(View.VISIBLE);
                    vb.topBar.setVisibility(View.GONE);
                    
                    // 切换到对应的Fragment（position-1因为底部只有2个Fragment）
                    switchBottomFragment(position - 1);
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                View customView = tab.getCustomView();
                if (customView == null) return;
                
                PagTabBinding tabVb = PagTabBinding.bind(customView);
                
                // 应用未选中效果
                applyUnselectedEffect(tabVb);
            }

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

            }
        });

        vb.imSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainViewActivity.this, SearchViewActivity.class);
                startActivity(intent);
            }
        });
    }

    /**
     * 应用统一的选中效果：显示背景框 + 图标放大
     */
    private void applySelectedEffect(com.wall.dream.wallpapers.databinding.PagTabBinding tabVb) {
        if (tabVb == null) return;
        
        // 显示统一的背景框
        if (tabVb.bgFrame != null) {
            tabVb.bgFrame.setVisibility(View.VISIBLE);
        }
        
        // 图标效果：放大一点，完全不透明
        if (tabVb.imageIcon != null) {
            tabVb.imageIcon.setColorFilter(ContextCompat.getColor(this, R.color.white));
            tabVb.imageIcon.setAlpha(1.0f);
            tabVb.imageIcon.setScaleX(1.1f);
            tabVb.imageIcon.setScaleY(1.1f);
        }
    }

    /**
     * 应用未选中效果：隐藏背景框 + 图标恢复原始大小
     */
    private void applyUnselectedEffect(com.wall.dream.wallpapers.databinding.PagTabBinding tabVb) {
        if (tabVb == null) return;
        
        // 隐藏背景框
        if (tabVb.bgFrame != null) {
            tabVb.bgFrame.setVisibility(View.GONE);
        }
        
        // 图标效果：恢复原始大小，降低透明度
        if (tabVb.imageIcon != null) {
            tabVb.imageIcon.setColorFilter(ContextCompat.getColor(this, R.color.white));
            tabVb.imageIcon.setAlpha(0.85f);
            tabVb.imageIcon.setScaleX(1.0f);
            tabVb.imageIcon.setScaleY(1.0f);
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        loadAd();
    }

    private void loadAd() {
        AdsInsUtil.INSTANCE.loadAd(this, AdsInsUtil.Placement.TOP_ON_AD_THREE, new LoadListener() {
            @Override
            public void loaded(@NotNull TPAdInfo 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 TPAdInfo ad) {

            }

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

            }
        });
    }
}