package com.droideve.apps.dealify.fragments;

import static com.droideve.apps.dealify.appconfig.AppConfig.APP_DEBUG;

import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentStatePagerAdapter;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.droideve.apps.dealify.R;
import com.droideve.apps.dealify.activities.LoginV2Activity;
import com.droideve.apps.dealify.activities.ProfileActivity;
import com.droideve.apps.dealify.animation.DepthPageTransformer;
import com.droideve.apps.dealify.appconfig.AppConfig;
import com.droideve.apps.dealify.appconfig.Constances;
import com.droideve.apps.dealify.classes.Category;
import com.droideve.apps.dealify.controllers.sessions.SessionsController;
import com.droideve.apps.dealify.utils.NSLog;
import com.droideve.apps.dealify.views.SwipeDisabledViewPager;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.ogaclejapan.smarttablayout.SmartTabLayout;

import org.greenrobot.eventbus.EventBus;

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


public class MainFragment extends Fragment {

    public final static String TAG = "mainfragment";
    private static ViewPager pager;
    private ViewPagerAdapter adapter;
    private SmartTabLayout tabs;
    private FragmentActivity myContext;
    private Listener mListener;

    public static ViewPager getPager() {
        return pager;
    }


    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main, container, false);

        // Creating The ViewPagerAdapter and Passing Fragment Manager, Titles fot the Tabs and Number Of Tabs.
        adapter = new ViewPagerAdapter(myContext.getSupportFragmentManager(),
                AppConfig.TabsConfig, AppConfig.TabsConfig.size());

        // Assigning ViewPager View and setting the adapter
        pager = rootView.findViewById(R.id.pager);
        pager.setAdapter(adapter);

        //Pager animation
        pager.setPageTransformer(true, new DepthPageTransformer());


        pager.setOffscreenPageLimit((Constances.initConfig.Numboftabs));
        pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                PageViewEvent mPageViewEvent = new PageViewEvent();
                //mPageViewEvent.position = position;
                mPageViewEvent.title = adapter.getPageTitle(position).toString();

                EventBus.getDefault().post(mPageViewEvent);
            }

            @Override
            public void onPageSelected(int position) {

            }

            @Override
            public void onPageScrollStateChanged(int state) {
                if (APP_DEBUG)
                    Log.e("onPageScrolledVP", "state" + state);
            }
        });

        // Assiging the Sliding Tab Layout View
        tabs = rootView.findViewById(R.id.tabs);
        tabs.setCustomTabView(new SmartTabLayout.TabProvider() {
            @Override
            public View createTabView(ViewGroup container, int position, PagerAdapter adapter) {
                ImageView icon = (ImageView) inflater.inflate(R.layout.custom_tab_icon1, container,
                        false);

                int drawableId = Constances.initConfig.ListCats.get(position).getIcon();
                icon.setImageDrawable(getResources().getDrawable(drawableId));

                return icon;
            }
        });

        // Setting the ViewPager For the SlidingTabsLayout
        tabs.setViewPager(pager);


        try {
            boolean chat = getActivity().getIntent().getExtras().getBoolean("chat", false);
            if (chat) {

                for (int i = 0; i < Constances.initConfig.Numboftabs; i++) {
                    if (AppConfig.TabsConfig.get(i).getNumCat() == -1) {
                        pager.setCurrentItem(i);
                    }
                }
            }

        } catch (Exception e) {

        }


        if (Constances.initConfig.Numboftabs == 1) {
            tabs.setVisibility(View.GONE);
        }

        tabs.setDistributeEvenly(false);

        return rootView;
    }


    public void setCurrentFragment(int position) {
        pager.setCurrentItem(position);
    }


    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        myContext = (FragmentActivity) activity;
    }

    @Override
    public void onStart() {
        super.onStart();

    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }

    @Override
    public void onPrepareOptionsMenu(Menu menu) {
        super.onPrepareOptionsMenu(menu);
        updateBadges();
    }


    private void updateBadges() {
        // MainActivity.updateMessengerBadge(this.get);
        // MainActivity.updateNotificationBadge(getActivity());
    }


    public class ViewPagerAdapter extends FragmentStatePagerAdapter {

        List<Category> tabsItems; // This will Store the Titles of the Tabs which are Going to be passed when ViewPagerAdapter is created
        int NumbOfTabs; // Store the number of tabs, this will also be passed when the ViewPagerAdapter is created

        List<Integer> nbrNotifis;

        // Build a Constructor and assign the passed Values to appropriate values in the class
        public ViewPagerAdapter(FragmentManager fm, List<Category> tabs, int mNumbOfTabsumb) {
            super(fm);

            this.tabsItems = tabs;
            this.NumbOfTabs = mNumbOfTabsumb;
            nbrNotifis = new ArrayList<>();


            for (int i = 0; i < NumbOfTabs; i++) {
                nbrNotifis.add(0);
            }
        }

        //This method return the fragment for the every position in the View Pager
        @Override
        public androidx.fragment.app.Fragment getItem(int position) {

            androidx.fragment.app.Fragment fragment = null;

            if (AppConfig.APP_DEBUG)
                Log.e("tab", String.valueOf(AppConfig.TabsConfig.get(position).getType()));

            if (AppConfig.TabsConfig.get(position).getType() == Constances.initConfig.Tabs.NEW_ORDERS) {

                fragment = new OrdersFragment();
                Bundle b = new Bundle();

                HashMap<String, String> listParams = new HashMap<>();
                listParams.put("order_by", Constances.OrderByFilter.NEARBY);
                listParams.put("order_status", Constances.ORDER_STATUS.CONFIRMED + "");
                listParams.put("delivery_status", Constances.DELIVERY_STATUS.PENDING + "");
                listParams.put("limit", AppConfig.NEW_ORDERS_MAX_NUM + "");
                b.putSerializable("params", listParams);
                b.putBoolean("expanded", true);

                fragment.setArguments(b);

            } else if (AppConfig.TabsConfig.get(position).getType() == Constances.initConfig.Tabs.ORDER_HISTORY) {
                fragment = new OrdersFragment();
                Bundle b = new Bundle();

                HashMap<String, String> listParams = new HashMap<>();
                listParams.put("order_by", Constances.OrderByFilter.RECENT);
                listParams.put("order_status", Constances.ORDER_STATUS.ALL + "");
                listParams.put("delivery_status", Constances.DELIVERY_STATUS.ALL + "");
                listParams.put("limit", AppConfig.HISTORY_ORDERS_MAX_NUM + "");
                listParams.put("delivery_id", SessionsController.getSession().getUser().getId() + "");

                b.putSerializable("params", listParams);
                b.putBoolean("expanded", false);

                fragment.setArguments(b);

            } else if (AppConfig.TabsConfig.get(position).getType() == Constances.initConfig.Tabs.CHAT) {

                if (SessionsController.isLogged()) fragment = new InboxFragment();
                else fragment = new LoginFragment();

            }


            return fragment;

            //return fragment;
        }

        // This method return the titles for the Tabs in the Tab Strip

        @Override
        public CharSequence getPageTitle(int position) {
            return tabsItems.get(position).getNameCat();
        }


        // This method return the Number of tabs for the tabs Strip

        @Override
        public int getCount() {
            return NumbOfTabs;
        }


    }

    public void setListener(final Listener mItemListener) {
        this.mListener = mItemListener;
    }

    public interface Listener {
        void onScrollHorizontal(int position);

        void onScrollVertical(int scrollXs, int scrollY);
    }

    public class PageViewEvent {
        public String title;
        public int position;
    }

}
