package com.droideve.apps.dealify.fragments;

import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.cardview.widget.CardView;
import androidx.core.widget.NestedScrollView;
import androidx.fragment.app.Fragment;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.bumptech.glide.Glide;
import com.droideve.apps.dealify.R;
import com.droideve.apps.dealify.Services.BusStation;
import com.droideve.apps.dealify.Services.NotifyDataNotificationEvent;
import com.droideve.apps.dealify.activities.CustomSearchActivity;
import com.droideve.apps.dealify.activities.ProductCartActivity;
import com.droideve.apps.dealify.activities.ResultFilterActivity;
import com.droideve.apps.dealify.animation.Animation;
import com.droideve.apps.dealify.appconfig.Constances;
import com.droideve.apps.dealify.classes.Category;
import com.droideve.apps.dealify.classes.Setting;
import com.droideve.apps.dealify.classes.User;
import com.droideve.apps.dealify.controllers.SettingsController;
import com.droideve.apps.dealify.controllers.categories.CategoryController;
import com.droideve.apps.dealify.controllers.sessions.SessionsController;
import com.droideve.apps.dealify.customview.CategoryCustomView;
import com.droideve.apps.dealify.customview.OfferCustomView;
import com.droideve.apps.dealify.customview.ProductCustomView;
import com.droideve.apps.dealify.customview.SliderCustomView;
import com.droideve.apps.dealify.customview.StoreCustomView;
import com.droideve.apps.dealify.navigationdrawer.NavigationDrawerFragment;
import com.droideve.apps.dealify.utils.BadgeNotificationUtils;
import com.github.siyamed.shapeimageview.RoundedImageView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.realm.RealmResults;

public class HomeFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener {

    public final static String TAG = "homefragment";
    //binding
    @BindView(R.id.mScroll)
    NestedScrollView mNestedScrollView;

    @BindView(R.id.lbox)
    LinearLayout lbox;

    @BindView(R.id.refresh)
    SwipeRefreshLayout refresh;

    @BindView(R.id.delivery_widget)
    CardView deliveryWidget;

    @BindView(R.id.deliver_app_name)
    TextView deliveryAppName;


    @OnClick(R.id.lbox)
    public void submit(View view) {
        getActivity().
        startActivity(new Intent(getActivity(), CustomSearchActivity.class));
    }

    private View rootview;
    private Listener mListener;

    // newInstance constructor for creating fragment with arguments
    public static HomeFragment newInstance(int page, String title) {
        HomeFragment fragmentFirst = new HomeFragment();
        Bundle args = new Bundle();
        args.putInt("id", page);
        args.putString("title", title);
        fragmentFirst.setArguments(args);
        return fragmentFirst;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.v2_fragment_home, container, false);
        rootview = rootView.getRootView();
        ButterKnife.bind(this, rootview);
        // Inflate the layout for this fragment
        setHasOptionsMenu(true);

        initSwipeRefresh();

        setupDeliveryWidget();

        setupScroll();

        initCategoryRV();

        initSliderCustomView();

        initFeaturedProductRv();

        initOfferRV();

        initRecentProductRv();

        initTopSellerProductRv();

        initStoreRV();

        initHeader();

        initViewContainer();


        return rootview;
    }

    private void initViewContainer() {
        RealmResults< Category> list = CategoryController.getTopSubCategories(3);
        LinearLayout container = rootview.findViewById(R.id.viewContainer);
        for (Category cat : list){
            ProductCustomView mProductCustomView = new ProductCustomView(getActivity(),
                    Map.of(
                            "pcvLimit",8,
                            "header",String.format(getResources().getString(R.string.product_for), cat.getNameCat()),
                            "displayHeader",true,
                            "height",getResources().getDimension(R.dimen.v2_product_card_height),
                            "width",getResources().getDimension(R.dimen.v2_product_card_width),
                            "loader",true
                    ));
            container.addView(mProductCustomView);
            HashMap<String, Object> optionalParams = new HashMap<>();
            optionalParams.put("category_id", cat.getNumCat());
            mProductCustomView.loadData(false, optionalParams);
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

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

    @Override
    public void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onPrepareOptionsMenu(Menu menu) {
        //update all badge
        updateBadges();
        //update cart icon in main fragment
        BadgeNotificationUtils.updateCartItemsBadgeView(rootview.findViewById(R.id.cartBadge));

        if (menu != null) {
            menu.findItem(R.id.list_view_icon).setVisible(false);
            menu.findItem(R.id.search_icon).setVisible(false);
            menu.findItem(R.id.notification_action).setVisible(true);
        }

        super.onPrepareOptionsMenu(menu);
    }

    private void updateBadges() {
        BadgeNotificationUtils.updateMessengerBadge(getActivity());
        BadgeNotificationUtils.updateNotificationBadge(getActivity());
        BadgeNotificationUtils.updateCartItemsBadge(getActivity());
    }

    private void setupDeliveryWidget() {

        (new Handler()).postDelayed(new Runnable() {
            @Override
            public void run() {
                Setting defaultAppSetting = SettingsController.findSettingFiled("DELIVERY_ANDROID_LINK");
                if (defaultAppSetting != null && !defaultAppSetting.getValue().equals("") ) {

                    deliveryAppName.setText(String.format(getContext().getResources().getString(R.string.delivery_name), getResources().getString(R.string.app_name)));
                    Animation.startZoomEffect(deliveryWidget);
                    //deliveryWidget.setVisibility(View.VISIBLE);

                    deliveryWidget.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(defaultAppSetting.getValue()));
                            startActivity(intent);
                        }
                    });
                } else {
                    deliveryWidget.setVisibility(View.GONE);
                }
            }
        }, 4000);


    }

    private void setupScroll() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            mNestedScrollView.setOnScrollChangeListener(new View.OnScrollChangeListener() {
                @Override
                public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                    Log.e(getTag(), scrollX + " - " + scrollY);

                    if (mListener != null)
                        mListener.onScroll(scrollX, scrollY);
                }
            });
        }
    }

    private void initCategoryRV() {
        CategoryCustomView mCategoryCustomView = rootview.findViewById(R.id.rectCategoryList);
        mCategoryCustomView.loadData(false);
        mCategoryCustomView.show();
    }

    private void initStoreRV() {
        StoreCustomView mStoreCustomView = rootview.findViewById(R.id.horizontalStoreList);
        mStoreCustomView.loadData(false);
        mStoreCustomView.show();
    }

    private void initOfferRV() {
        OfferCustomView mOfferCustomView = rootview.findViewById(R.id.horizontalOfferList);
        if (!SettingsController.isModuleEnabled(Constances.ModulesConfig.OFFER_MODULE)) {
            mOfferCustomView.hide();
        } else {
            mOfferCustomView.loadData(false, new HashMap<>());
            mOfferCustomView.show();
        }
    }

    private void initSliderCustomView() {
        SliderCustomView mSliderCustomView = rootview.findViewById(R.id.sliderCV);

        if (!SettingsController.isModuleEnabled(Constances.ModulesConfig.SLIDER_MODULE)) {
            mSliderCustomView.hide();
        } else {
            mSliderCustomView.loadData(false);
            mSliderCustomView.startAutoSlider();

            mSliderCustomView.show();
        }
    }

    private void initRecentProductRv() {

        ProductCustomView mProductCustomView = rootview.findViewById(R.id.recentProductList);
        if (!SettingsController.isModuleEnabled(Constances.ModulesConfig.PRODUCT_MODULE)) {
            mProductCustomView.hide();
        } else {
            HashMap<String, Object> optionalParams = new HashMap<>();
            optionalParams.put("is_featured", 0);
            mProductCustomView.loadData(false, optionalParams);
            mProductCustomView.show();
        }
    }

    private void initTopSellerProductRv() {

        ProductCustomView mProductCustomView = rootview.findViewById(R.id.topSellerProductList);
        if (!SettingsController.isModuleEnabled(Constances.ModulesConfig.PRODUCT_MODULE)) {
            mProductCustomView.hide();
        } else {
            HashMap<String, Object> optionalParams = new HashMap<>();
            optionalParams.put("is_featured", -1);
            optionalParams.put("order_by", "top_seller");
            mProductCustomView.loadData(false, optionalParams);
            mProductCustomView.show();
        }
    }




    private void initHeader() {

        RoundedImageView mUserImageView = rootview.findViewById(R.id.headerUserImage);
        TextView mUserNameView = rootview.findViewById(R.id.headerUserName);

        if(SessionsController.isLogged()){
            User user =  SessionsController.getSession().getUser();
            //set name
            String username = user.getName().replaceAll(" ", "\n");
            mUserNameView.setText(username);
            //set image
            if (user.getImages() != null) {
                Glide.with(getActivity()).load(user.getImages().getUrl500_500())
                        .placeholder(R.drawable.profile_placeholder)
                        .centerCrop().into(mUserImageView);
            }
        }

        //click on  profile and open navigation
        rootview.findViewById(R.id.topLeftNavigationProfile).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BusStation.getBus().post(new NavigationDrawerFragment.NavigationDrawerEvent(1));
            }
        });

        //Open Cart Activity
        rootview.findViewById(R.id.topLeftNavigationCart).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), ProductCartActivity.class);
                startActivity(intent);
            }
        });

        //Open Filter Activity
        rootview.findViewById(R.id.cardFilter).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), CustomSearchActivity.class);
                intent.putExtra("selected_module", Constances.ModulesConfig.PRODUCT_MODULE);
                startActivity(intent);
            }
        });

        //search bar listeners
        ((EditText) rootview.findViewById(R.id.searchInput)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ((EditText) v).requestFocus();
                ((EditText) v).setImeActionLabel("Search", EditorInfo.IME_ACTION_UNSPECIFIED);
                ((EditText) rootview.findViewById(R.id.searchInput)).setFocusableInTouchMode(true);
                ((EditText) rootview.findViewById(R.id.searchInput)).setFocusable(true);
            }
        });

        //editor listner
        ((EditText) rootview.findViewById(R.id.searchInput)).setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    performSearch();
                    return true;
                }
                return false;
            }
        });


    }

    //Header: open result interface
    private void performSearch() {

        HashMap<String, Object> searchParams = new HashMap<>();
        searchParams.put("search", ((EditText) rootview.findViewById(R.id.searchInput)).getText().toString().trim());
        searchParams.put("module", "product"); //assign module

        //searchParams
        Intent intent = new Intent(getActivity(), ResultFilterActivity.class);
        intent.putExtra("searchParams", searchParams);
        startActivity(intent);

    }

    private void initFeaturedProductRv() {
        ProductCustomView mFeaturedProductCustomView = rootview.findViewById(R.id.featured_products);
        if (!SettingsController.isModuleEnabled(Constances.ModulesConfig.PRODUCT_MODULE)) {
            mFeaturedProductCustomView.hide();
        } else {

            HashMap<String, Object> optionalParams = new HashMap<>();
            optionalParams.put("is_featured", 1);
            mFeaturedProductCustomView.loadData(false, optionalParams);
            mFeaturedProductCustomView.show();
        }
    }

    @Override
    public void onRefresh() {

        initCategoryRV();

        initSliderCustomView();

        initFeaturedProductRv();

        initOfferRV();

        initRecentProductRv();
        initTopSellerProductRv();

        initStoreRV();

        //end refreshing
        refresh.setRefreshing(false);

    }

    private void initSwipeRefresh() {

        refresh.setOnRefreshListener(this);
        refresh.setColorSchemeResources(
                R.color.colorPrimary,
                R.color.colorPrimary,
                R.color.colorPrimary,
                R.color.colorPrimary
        );

    }

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

    public interface Listener {
        void onScroll(int scrollX, int scrollY);
    }

    @Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
    public void onMessageEvent(NotifyDataNotificationEvent event) {
        if (event.message != null && event.message.equals("cart_badge_counter")) {
            BadgeNotificationUtils.updateCartItemsBadgeView(rootview.findViewById(R.id.cartBadge));
        }
    }
}
