package com.gh.gamecenter.common.base.fragment;

import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CheckedTextView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.gh.gamecenter.common.R;
import com.gh.gamecenter.common.base.adapter.FragmentAdapter;
import com.gh.gamecenter.common.view.TabIndicatorView;
import com.google.android.material.tabs.TabLayout;
import com.lightgame.utils.Utils;
import com.lightgame.view.NoScrollableViewPager;

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

/**
 * Created by khy on 15/03/18.
 */

public abstract class BaseFragment_TabLayout extends ToolbarFragment implements ViewPager.OnPageChangeListener {

    public static final String PAGE_INDEX = "PAGE_INDEX";

    protected TabLayout mTabLayout;
    protected NoScrollableViewPager mViewPager;
    protected TabIndicatorView mTabIndicatorView;
    @Nullable
    protected View mDividerLineView;

    protected List<Fragment> mFragmentsList;

    protected List<String> mTabTitleList;

    protected int mCheckedIndex = 0;

    protected abstract void initFragmentList(List<Fragment> fragments);

    protected abstract void initTabTitleList(List<String> tabTitleList);

    protected int provideIndicatorWidth() {
        return 20;
    }

    protected View provideTabView(int position, String tabTitle) {
        return null;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_tablayout_viewpager;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        List<Fragment> fragments = getChildFragmentManager().getFragments();
        if (fragments != null) {
            for (Fragment fragment : fragments) {
                fragment.onActivityResult(requestCode, resultCode, data);
            }
        }
    }

    private ArrayList<Fragment> restoreFragments() {
        String tag = "android:switcher:" + mViewPager.getId() + ":";
        ArrayList<Fragment> fragments = new ArrayList<>();
        int childCount = mTabTitleList.size();
        for (int index = 0; index < childCount; index++) {
            Fragment fragment = getChildFragmentManager().findFragmentByTag(tag + index);
            if (fragment != null) {
                fragments.add(fragment);
            }
        }

        return fragments;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        mTabLayout = view.findViewById(R.id.fragment_tab_layout);
        mViewPager = view.findViewById(R.id.fragment_view_pager);
        mTabIndicatorView = view.findViewById(R.id.fragment_tab_indicator);
        mDividerLineView = view.findViewById(R.id.dividerLine);

        if (getArguments() != null) mCheckedIndex = getArguments().getInt(PAGE_INDEX, 0);
        mTabTitleList = new ArrayList<>();
        initTabTitleList(mTabTitleList);
        mFragmentsList = new ArrayList<>(restoreFragments());
        if (mFragmentsList.isEmpty() || mFragmentsList.size() != mTabTitleList.size()) {
            mFragmentsList.clear();
            initFragmentList(mFragmentsList);
        }

        mViewPager.setOffscreenPageLimit(mFragmentsList.size());
        mViewPager.addOnPageChangeListener(this);
        mViewPager.setAdapter(new FragmentAdapter(getChildFragmentManager(), mFragmentsList, mTabTitleList));
        mViewPager.setCurrentItem(mCheckedIndex);
        mTabLayout.setupWithViewPager(mViewPager);
        mTabIndicatorView.setupWithTabLayout(mTabLayout);
        mTabIndicatorView.setupWithViewPager(mViewPager);
        mTabIndicatorView.setIndicatorWidth(provideIndicatorWidth());

        for (int i = 0; i < mTabLayout.getTabCount(); i++) {
            TabLayout.Tab tab = mTabLayout.getTabAt(i);
            if (tab == null) continue;
            String tabTitle = tab.getText() != null ? tab.getText().toString() : "";
            View tabView = provideTabView(i, tabTitle);
            if (tabView == null) tabView = createDefaultTabCustomView(requireContext(), tabTitle);
            tab.setCustomView(tabView);
        }

        initTabStyle(mTabLayout, mCheckedIndex);
    }

    public static void initTabStyle(TabLayout tabLayout, int currentItem) {
        // 默认选择addOnTabSelectedListener不会回调
        int tabCount = tabLayout.getTabCount();
        if (tabCount > 0) {
            TabLayout.Tab tab = tabLayout.getTabAt(currentItem);
            if (tab != null) updateTabStyle(tab, true);
        }

        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                updateTabStyle(tab, true);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                updateTabStyle(tab, false);
            }

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

    public static void updateTabStyle(TabLayout.Tab tab, boolean isChecked) {
        View tabView = tab.getCustomView();
        if (tabView == null) {
            Utils.log("TabLayout->Tab样式不是通用样式,请检查");
            return;
        }

        TextView tabTitle;
        if (tabView instanceof TextView) {
            tabTitle = (TextView) tabView;
        } else {
            tabTitle = tabView.findViewById(R.id.tab_title);
        }

        if (tabTitle == null) {
            Utils.log("TabLayout->Tab样式不是通用样式,请检查");
            return;
        }
        tabTitle.setTypeface(isChecked ? Typeface.DEFAULT_BOLD : Typeface.DEFAULT);
        tabTitle.setTextColor(ContextCompat.getColor(tabTitle.getContext(), isChecked ? R.color.theme_font : R.color.text_subtitle));
    }

    // 如果不设置View的话，无法动态设置字体样式
    @NonNull
    public static View createDefaultTabCustomView(Context context, String title) {
        View view = LayoutInflater.from(context).inflate(R.layout.tab_item, null);
        View tabTitle = view.findViewById(R.id.tab_title);
        if (tabTitle instanceof CheckedTextView) {
            ((CheckedTextView) tabTitle).setText(title);
        }
        return view;
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {

    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @Override
    protected void onDarkModeChanged() {
        super.onDarkModeChanged();
        View container = requireView().findViewById(R.id.fragment_tab_container);
        if (container != null) {
            container.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.background_white));
            for (int i = 0; i < mTabLayout.getTabCount(); i++) {
                TabLayout.Tab tab = mTabLayout.getTabAt(i);
                if (tab != null) {
                    updateTabStyle(tab, tab.isSelected());
                }
            }
        }
        if (mDividerLineView != null) {
            mDividerLineView.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.divider));
        }
    }
}
