package com.atmob.voiceai.module.main;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.atmob.app.lib.base.BaseActivity;
import com.atmob.voiceai.R;
import com.atmob.voiceai.data.api.bean.CloneVoiceListBean;
import com.atmob.voiceai.data.consts.EventId;
import com.atmob.voiceai.data.repositories.CloneRepository;
import com.atmob.voiceai.databinding.ActivityMainBinding;
import com.atmob.voiceai.databinding.ItemMainTabLayoutBinding;
import com.atmob.voiceai.handlers.EventHandler;
import com.atmob.voiceai.module.clonevoice.CloneVoiceFragment;
import com.atmob.voiceai.module.history.HistoryFragment;
import com.atmob.voiceai.module.voiceai.VoiceAIFragment;
import com.atmob.voiceai.utils.ToastUtil;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import com.gyf.immersionbar.ImmersionBar;

import java.util.List;

import dagger.hilt.android.AndroidEntryPoint;


@AndroidEntryPoint
public class MainActivity extends BaseActivity<ActivityMainBinding> {

    private long mExitTime;
    private MainViewModel mainViewModel;
    private static final String TO_TAB_FRAGMENT = "to_tab_fragment";
    private TabLayoutMediator tabLayoutMediator;
    private MainPagerAdapter mainPagerAdapter;

    public static void start(Context context) {
        Intent intent = new Intent(context, MainActivity.class);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }

    public static void start(Context context, Class<? extends Fragment> cls) {
        Intent intent = new Intent(context, MainActivity.class);
        if (!(context instanceof android.app.Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        if (cls != null) {
            intent.putExtra(TO_TAB_FRAGMENT, cls);
        }
        context.startActivity(intent);
    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (intent != null) {
            Class<? extends Fragment> cls = (Class<? extends Fragment>) intent.getSerializableExtra(TO_TAB_FRAGMENT);
            if (cls != null) {
                binding.mainTabLayout.selectTab(binding.mainTabLayout.getTabAt(mainPagerAdapter.getPosition(cls)));
            }
        }
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
        initObserver();
    }

    private void initObserver() {

    }


    private void initView() {
        initViewPager();
        initTabLayout();
    }

    private void initViewPager() {
        mainPagerAdapter = new MainPagerAdapter(this);
        binding.mainViewPager.setAdapter(mainPagerAdapter);
        binding.mainViewPager.setUserInputEnabled(false);
        binding.mainViewPager.setOffscreenPageLimit(mainPagerAdapter.getItemCount());
    }


    private void initTabLayout() {
        binding.mainTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                ItemMainTabLayoutBinding itemBinding = (ItemMainTabLayoutBinding) tab.getTag();
                if (itemBinding != null) {
                    itemBinding.tabText.setSelected(true);
                    itemBinding.tabIcon.setSelected(true);
                }
                Class<? extends Fragment> pagerClass = mainPagerAdapter.getMainPagerItemByPosition(tab.getPosition()).getPagerClass();
                if (VoiceAIFragment.class.equals(pagerClass)) {
                    EventHandler.report(EventId.hometab_001);
                } else if (CloneVoiceFragment.class.equals(pagerClass)) {
                    List<CloneVoiceListBean> value = CloneRepository.getCloneRepository().getCloneVoiceList().getValue();
                    if (value != null && !value.isEmpty()) {
                        EventHandler.report(EventId.clonedone_001);
                    } else {
                        EventHandler.report(EventId.cloneundone_001);
                    }
                } else if (HistoryFragment.class.equals(pagerClass)) {
                    EventHandler.report(EventId.history_001);
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                ItemMainTabLayoutBinding itemBinding = (ItemMainTabLayoutBinding) tab.getTag();
                if (itemBinding != null) {
                    itemBinding.tabText.setSelected(false);
                    itemBinding.tabIcon.setSelected(false);
                }
            }

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

            }
        });
        tabLayoutMediator = new TabLayoutMediator(binding.mainTabLayout, binding.mainViewPager, true, false, (tab, position) -> {
            MainPagerAdapter.MainPagerItem mainPagerItem = mainPagerAdapter.getMainPagerItemByPosition(position);
            ItemMainTabLayoutBinding itemBinding = ItemMainTabLayoutBinding.inflate(getLayoutInflater());
            itemBinding.tabText.setText(mainPagerItem.getTabName());
            itemBinding.tabIcon.setImageResource(mainPagerItem.getTabIcon());
            tab.setCustomView(itemBinding.getRoot());
            tab.setTag(itemBinding);
        });
        tabLayoutMediator.attach();
    }

    @Override
    protected void initViewModel() {
        super.initViewModel();
        mainViewModel = getViewModelProvider().get(MainViewModel.class);
    }

    @Override
    protected void configImmersion(@NonNull ImmersionBar immersionBar) {
        super.configImmersion(immersionBar);
        immersionBar.statusBarDarkFont(false);
    }

    @Override
    protected boolean shouldImmersion() {
        return true;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            exit();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    public void exit() {
        if ((System.currentTimeMillis() - mExitTime) > 2000) {
            ToastUtil.show(R.string.exit_application_text, ToastUtil.LENGTH_LONG);
            mExitTime = System.currentTimeMillis();
        } else {
            try {
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_MAIN);
                intent.addCategory(Intent.CATEGORY_HOME);
                startActivity(intent);
            } catch (Exception ignore) {
            }
        }
    }
}
