package com.idle.wall.idleactivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
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.ad.AdsInsUtil;
import com.idle.wall.ad.LoadListener;
import com.idle.wall.idlefragment.FragmentCategoryPage;
import com.idle.wall.idlefragment.FragmentIdlePage;
import com.idle.wall.idlefragment.FragmentIdleSetting;
import com.idle.wall.idletool.Comutils;
import com.tradplus.ads.base.bean.TPAdInfo;

import org.jetbrains.annotations.NotNull;

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

public class IdleMainActivity extends AppCompatActivity {
    private LinearLayout homeTabContainer;
    private ViewPager2 mainViewPager;
    private List<String> categoryNames = new ArrayList<>();
    private int currentCategoryPos = 0;
    private List<TextView> categoryTabList = new ArrayList<>();
    private ImageView tvAllCategoryBtn;
    private LinearLayout llDropdownCategoryList;
    private HorizontalScrollView categoryScrollView;
    private boolean isDropdownExpanded = false;
    private final float NORMAL_TEXT_SIZE = 14f;
    private final float SELECTED_TEXT_SIZE = 18f;
    private int unifiedTabWidth;
    private ImageView tabHome,tabMine, tabSetting;
    private int currentBottomTab = 0;
    private ImageView imSearch;
    // 新增：顶部标题文本View
    private TextView textviewWallpaper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Comutils.initFull(this, false);
        setContentView(R.layout.activity_idle_main);

        initViews();
        homeTabContainer.setVisibility(View.GONE);
        IdleApp.registerDataLoadedListener(new IdleApp.OnDataLoadedListener() {
            @Override
            public void onCoreDataLoaded() {
                runOnUiThread(() -> {
                    loadCategoryData();
                    calculateUnifiedTabWidth();
                    createCategoryTabs();
                    initDropdownCategoryList();
                    initAllCategoryButton();
                    initMainViewPager();
                    updateCategoryTabSelection(currentCategoryPos);
                    homeTabContainer.setVisibility(View.VISIBLE);
                });
            }

            @Override
            public void onAllDataLoaded() {
                runOnUiThread(() -> {
                    loadCategoryData();
                    calculateUnifiedTabWidth();
                    createCategoryTabs();
                    initDropdownCategoryList();
                    updateCategoryTabSelection(currentCategoryPos);
                    if (mainViewPager != null && mainViewPager.getAdapter() != null) {
                        mainViewPager.getAdapter().notifyDataSetChanged();
                    }
                    scrollToCategoryTab(0);
                });
            }
        });

        initBottomTabClick();
        handleIntentParams(getIntent());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        IdleApp.unregisterDataLoadedListener(new IdleApp.OnDataLoadedListener() {
            @Override
            public void onCoreDataLoaded() {}
            @Override
            public void onAllDataLoaded() {}
        });
        if (mainViewPager != null) {
            mainViewPager.unregisterOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {});
        }
        categoryTabList.clear();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        handleIntentParams(intent);
    }

    private void handleIntentParams(Intent intent) {
        if (intent == null) return;
        boolean switchToHome = intent.getBooleanExtra("KEY_SWITCH_TO_HOME_TAB", false);
        if (switchToHome && currentBottomTab != 0) {
            currentBottomTab = 0;
            updateBottomTabSelection(0);
            // 新增：切换到首页时更新标题
            updateTopTitleText(0);
            homeTabContainer.setVisibility(View.VISIBLE);
            initMainViewPager();
            mainViewPager.setCurrentItem(0, false);
            updateCategoryTabSelection(0);
            if (isDropdownExpanded) {
                toggleDropdown(false);
            }
            if (imSearch != null) {
                imSearch.setVisibility(View.VISIBLE);
            }
        }
    }

    private void initViews() {
        categoryScrollView = findViewById(R.id.category_scroll_view);
        homeTabContainer = findViewById(R.id.home_tab_container);
        tvAllCategoryBtn = findViewById(R.id.tv_all_category_btn);
        llDropdownCategoryList = findViewById(R.id.ll_dropdown_category_list);
        mainViewPager = findViewById(R.id.viewpager2);
        tabHome = findViewById(R.id.tab_home);
        tabMine = findViewById(R.id.tab_mine);
        tabSetting = findViewById(R.id.tab_setting);
        imSearch = findViewById(R.id.im_search);
        // 新增：初始化顶部标题View
        textviewWallpaper = findViewById(R.id.textview_wallpaper);

        if (imSearch != null) {
            imSearch.setOnClickListener(v -> {
                Intent intent = new Intent(IdleMainActivity.this, IdleSearchActivity.class);
                startActivity(intent);
            });
            imSearch.setVisibility(View.VISIBLE);
        }

        updateBottomTabSelection(0);
        // 新增：初始化首页标题
        updateTopTitleText(0);
        homeTabContainer.setVisibility(View.VISIBLE);
        if (categoryScrollView != null) {
            categoryScrollView.setHorizontalScrollBarEnabled(false);
            categoryScrollView.setVerticalScrollBarEnabled(false);
            categoryScrollView.setOverScrollMode(View.OVER_SCROLL_NEVER);
        }
    }

    // 新增：更新顶部标题文本的方法
    private void updateTopTitleText(int tabType) {
        if (textviewWallpaper == null) return;
        switch (tabType) {
            case 0: // 首页
                textviewWallpaper.setText(R.string.app_name);
                break;
            case 1: // 我的
                textviewWallpaper.setText(R.string.my_name);
                break;
            case 2: // 设置
                textviewWallpaper.setText(R.string.setting);
                break;
            default:
                textviewWallpaper.setText(R.string.app_name);
                break;
        }
    }

    private void loadCategoryData() {
        categoryNames = IdleApp.getCategoryNames();
        homeTabContainer.removeAllViews();
        categoryTabList.clear();
    }

    private void calculateUnifiedTabWidth() {
        if (categoryNames.isEmpty()) return;

        String longestName = "";
        for (String name : categoryNames) {
            if (name.length() > longestName.length()) {
                longestName = name;
            }
        }
        TextView tempTab = new TextView(this);
        tempTab.setText(longestName);
        tempTab.setTextSize(NORMAL_TEXT_SIZE);
        tempTab.setPadding(
                Comutils.dp2px(this, 14),
                Comutils.dp2px(this, 10),
                Comutils.dp2px(this, 14),
                Comutils.dp2px(this, 10)
        );
        int widthMeasureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        int heightMeasureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        tempTab.measure(widthMeasureSpec, heightMeasureSpec);
        unifiedTabWidth = tempTab.getMeasuredWidth() + Comutils.dp2px(this, 10);
    }

    private void createCategoryTabs() {
        if (categoryNames.isEmpty() || unifiedTabWidth == 0) return;
        LinearLayout.LayoutParams tabParams = new LinearLayout.LayoutParams(
                unifiedTabWidth,
                ViewGroup.LayoutParams.WRAP_CONTENT
        );
        int margin = Comutils.dp2px(this, 8);
        tabParams.setMargins(margin, 0, margin, 0);
        tabParams.gravity = Gravity.CENTER_VERTICAL;

        for (int i = 0; i < categoryNames.size(); i++) {
            String cateName = categoryNames.get(i);
            TextView tabView = new TextView(this);
            tabView.setText(cateName);
            tabView.setTextSize(NORMAL_TEXT_SIZE);
            tabView.setPadding(
                    Comutils.dp2px(this, 12),
                    Comutils.dp2px(this, 8),
                    Comutils.dp2px(this, 12),
                    Comutils.dp2px(this, 8)
            );
            tabView.setLayoutParams(tabParams);
            tabView.setClickable(true);
            tabView.setFocusable(true);
            tabView.setTag(i);
            tabView.setGravity(Gravity.CENTER);
            tabView.setSingleLine(true);
            tabView.setOnClickListener(v -> {
                if (currentBottomTab != 0) return;
                int position = (int) v.getTag();
                switchToCategory(position);
                if (isDropdownExpanded) {
                    toggleDropdown(false);
                }
            });

            homeTabContainer.addView(tabView);
            categoryTabList.add(tabView);
        }
    }

    private void initDropdownCategoryList() {
        if (llDropdownCategoryList == null || categoryNames.isEmpty()) return;
        llDropdownCategoryList.removeAllViews();
        int itemMargin = Comutils.dp2px(this, 4);

        for (int i = 0; i < categoryNames.size(); i++) {
            String cateName = categoryNames.get(i);
            TextView tvItem = new TextView(this);
            tvItem.setText(cateName);
            tvItem.setTextSize(14);
            tvItem.setTextColor(currentCategoryPos == i ?
                    getResources().getColor(R.color.white) :
                    getResources().getColor(R.color.black));
            tvItem.setBackgroundResource(currentCategoryPos == i ?
                    R.drawable.tab_selected_bg1 :
                    R.drawable.bg_idle_round);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT
            );
            params.setMargins(itemMargin, itemMargin, itemMargin, itemMargin);
            tvItem.setLayoutParams(params);
            tvItem.setTag(i);
            tvItem.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);
            tvItem.setSingleLine(true);
            tvItem.setOnClickListener(v -> {
                int position = (int) v.getTag();
                switchToCategory(position);
                toggleDropdown(false);
            });

            llDropdownCategoryList.addView(tvItem);
        }
    }

    private void initAllCategoryButton() {
        if (tvAllCategoryBtn == null) return;
        tvAllCategoryBtn.setImageResource(R.drawable.all);
        tvAllCategoryBtn.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
        tvAllCategoryBtn.setBackgroundResource(R.drawable.bg_idle_round);
        tvAllCategoryBtn.setPadding(
                Comutils.dp2px(this, 6),
                Comutils.dp2px(this, 4),
                Comutils.dp2px(this, 6),
                Comutils.dp2px(this, 4)
        );

        tvAllCategoryBtn.setOnClickListener(v -> {
            if (currentBottomTab != 0) return;
            isDropdownExpanded = !isDropdownExpanded;
            toggleDropdown(isDropdownExpanded);
        });
    }

    private void toggleDropdown(boolean expand) {
        if (llDropdownCategoryList == null || tvAllCategoryBtn == null) return;
        llDropdownCategoryList.setVisibility(expand ? View.VISIBLE : View.GONE);
        if (expand) {
            tvAllCategoryBtn.setImageResource(R.drawable.all_two);
            tvAllCategoryBtn.setBackgroundResource(R.drawable.tab_selected_bg1);
            tvAllCategoryBtn.setPadding(
                    Comutils.dp2px(this, 7),
                    Comutils.dp2px(this, 5),
                    Comutils.dp2px(this, 7),
                    Comutils.dp2px(this, 5)
            );
        } else {
            tvAllCategoryBtn.setImageResource(R.drawable.all);
            tvAllCategoryBtn.setBackgroundResource(R.drawable.bg_idle_round);
            tvAllCategoryBtn.setPadding(
                    Comutils.dp2px(this, 6),
                    Comutils.dp2px(this, 4),
                    Comutils.dp2px(this, 6),
                    Comutils.dp2px(this, 4)
            );
        }
    }

    private void switchToCategory(int position) {
        if (currentCategoryPos != position) {
            currentCategoryPos = position;
            if (position < categoryTabList.size()) {
                updateCategoryTabSelection(position);
            } else {
                resetCategoryTabSelection();
            }
            updateDropdownSelection(position);
            mainViewPager.setCurrentItem(position, true);
            if (position < categoryTabList.size()) {
                scrollToCategoryTab(position);
            }
        }
    }

    private void updateDropdownSelection(int selectedPos) {
        if (llDropdownCategoryList == null) return;

        for (int i = 0; i < llDropdownCategoryList.getChildCount(); i++) {
            View itemView = llDropdownCategoryList.getChildAt(i);
            if (itemView instanceof TextView) {
                TextView tvItem = (TextView) itemView;
                int position = (int) tvItem.getTag();

                if (position == selectedPos) {
                    tvItem.setTextColor(getResources().getColor(R.color.white));
                    tvItem.setBackgroundResource(R.drawable.tab_selected_bg1);
                } else {
                    tvItem.setTextColor(getResources().getColor(R.color.black));
                    tvItem.setBackgroundResource(R.drawable.bg_idle_round);
                }
            }
        }
    }

    private void resetCategoryTabSelection() {
        for (TextView tab : categoryTabList) {
            tab.setTextSize(NORMAL_TEXT_SIZE);
            tab.setTextColor(getResources().getColor(R.color.sub_title_color));
            tab.setBackgroundResource(R.drawable.bg_idle_round);
            tab.setPadding(
                    Comutils.dp2px(this, 12),
                    Comutils.dp2px(this, 8),
                    Comutils.dp2px(this, 12),
                    Comutils.dp2px(this, 8)
            );
        }
    }

    private void updateCategoryTabSelection(int selectedPos) {
        if (categoryTabList.isEmpty() || selectedPos >= categoryTabList.size()) return;

        for (int i = 0; i < categoryTabList.size(); i++) {
            TextView tab = categoryTabList.get(i);
            if (i == selectedPos) {
                tab.setTextSize(SELECTED_TEXT_SIZE);
                tab.setTextColor(getResources().getColor(R.color.white));
                tab.setBackgroundResource(R.drawable.tab_selected_bg1);
                tab.setPadding(
                        Comutils.dp2px(this, 14),
                        Comutils.dp2px(this, 10),
                        Comutils.dp2px(this, 14),
                        Comutils.dp2px(this, 10)
                );
            } else {
                tab.setTextSize(NORMAL_TEXT_SIZE);
                tab.setTextColor(getResources().getColor(R.color.sub_title_color));
                tab.setBackgroundResource(R.drawable.bg_idle_round);
                tab.setPadding(
                        Comutils.dp2px(this, 12),
                        Comutils.dp2px(this, 8),
                        Comutils.dp2px(this, 12),
                        Comutils.dp2px(this, 8)
                );
            }
        }
    }

    private void initMainViewPager() {
        mainViewPager.setAdapter(new FragmentStateAdapter(this) {
            @Override
            public int getItemCount() {
                return currentBottomTab == 0 ? categoryNames.size() : 1;
            }

            @Override
            public Fragment createFragment(int position) {
                switch (currentBottomTab) {
                    case 0:
                        return FragmentCategoryPage.newInstance(categoryNames.get(position));
                    case 1:
                        return new FragmentIdlePage();
                    case 2:
                        return new FragmentIdleSetting();
                    default:
                        return FragmentCategoryPage.newInstance(categoryNames.get(0));
                }
            }
        });

        mainViewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                if (currentBottomTab == 0 && currentCategoryPos != position) {
                    switchToCategory(position);
                    if (isDropdownExpanded) {
                        toggleDropdown(false);
                    }
                }
            }
        });

        mainViewPager.setOffscreenPageLimit(2);
        mainViewPager.setUserInputEnabled(currentBottomTab == 0);
    }

    private void scrollToCategoryTab(int position) {
        if (position < categoryTabList.size() && categoryScrollView != null) {
            TextView selectedTab = categoryTabList.get(position);
            int scrollX = selectedTab.getLeft() - (categoryScrollView.getWidth() / 2) + (selectedTab.getWidth() / 2);
            categoryScrollView.smoothScrollTo(scrollX, 0);
        }
    }

    private void initBottomTabClick() {
        tabHome.setOnClickListener(v -> {
            if (currentBottomTab != 0) {
                currentBottomTab = 0;
                updateBottomTabSelection(0);
                // 新增：切换到首页更新标题
                updateTopTitleText(0);
                homeTabContainer.setVisibility(View.VISIBLE);
                initMainViewPager();
                mainViewPager.setCurrentItem(0, false);
                updateCategoryTabSelection(0);
                if (isDropdownExpanded) {
                    toggleDropdown(false);
                }
                // 切换到首页：显示搜索图标
                if (imSearch != null) {
                    imSearch.setVisibility(View.VISIBLE);
                }
            }
        });

        tabMine.setOnClickListener(v -> {
            if (currentBottomTab != 1) {
                currentBottomTab = 1;
                updateBottomTabSelection(1);
                // 新增：切换到我的更新标题
                updateTopTitleText(1);
                homeTabContainer.setVisibility(View.GONE);
                initMainViewPager();
                mainViewPager.setCurrentItem(0, false);
                if (isDropdownExpanded) {
                    toggleDropdown(false);
                }
                // 切换到我的：隐藏搜索图标
                if (imSearch != null) {
                    imSearch.setVisibility(View.GONE);
                }
            }
        });

        tabSetting.setOnClickListener(v -> {
            if (currentBottomTab != 2) {
                currentBottomTab = 2;
                updateBottomTabSelection(2);
                // 新增：切换到设置更新标题
                updateTopTitleText(2);
                homeTabContainer.setVisibility(View.GONE);
                initMainViewPager();
                mainViewPager.setCurrentItem(0, false);
                if (isDropdownExpanded) {
                    toggleDropdown(false);
                }
                if (imSearch != null) {
                    imSearch.setVisibility(View.GONE);
                }
            }
        });
    }

    private void updateBottomTabSelection(int selectedTab) {
        resetBottomTabStyle();
        switch (selectedTab) {
            case 0:
                tabHome.setImageResource(R.drawable.home_n);
                tabMine.setImageResource(R.drawable.mine_y);
                tabSetting.setImageResource(R.drawable.set_y);
                tabHome.setBackgroundResource(R.drawable.tab_selected_bg1);
                if (tvAllCategoryBtn != null) {
                    tvAllCategoryBtn.setVisibility(View.VISIBLE);
                }
                break;
            case 1:
                tabHome.setImageResource(R.drawable.home_y);
                tabMine.setImageResource(R.drawable.mine_n);
                tabSetting.setImageResource(R.drawable.set_y);
                tabMine.setBackgroundResource(R.drawable.tab_selected_bg1);
                if (tvAllCategoryBtn != null) {
                    tvAllCategoryBtn.setVisibility(View.GONE);
                }
                if (isDropdownExpanded) {
                    toggleDropdown(false);
                }
                break;
            case 2:
                tabHome.setImageResource(R.drawable.home_y);
                tabMine.setImageResource(R.drawable.mine_y);
                tabSetting.setImageResource(R.drawable.set_n);
                tabSetting.setBackgroundResource(R.drawable.tab_selected_bg1);
                if (tvAllCategoryBtn != null) {
                    tvAllCategoryBtn.setVisibility(View.GONE);
                }
                if (isDropdownExpanded) {
                    toggleDropdown(false);
                }
                break;
        }
    }

    private void resetBottomTabStyle() {
        tabHome.setImageResource(R.drawable.home_n);
        tabHome.setBackgroundResource(R.drawable.bg_idle_round);
        tabMine.setBackgroundResource(R.drawable.bg_idle_round);
        tabMine.setImageResource(R.drawable.mine_n);
        tabSetting.setBackgroundResource(R.drawable.bg_idle_round);
        tabSetting.setImageResource(R.drawable.set_n);
    }


    @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) {

            }
        });
    }
}