package ch.pizzalemon.android.activity;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import androidx.annotation.NonNull;
import com.google.android.material.bottomnavigation.BottomNavigationView;

import androidx.core.view.WindowCompat;
import androidx.fragment.app.FragmentManager;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import android.os.Bundle;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindColor;
import butterknife.BindDrawable;
import butterknife.BindView;
import butterknife.ButterKnife;
import ch.pizzalemon.android.R;
import ch.pizzalemon.android.adapter.recycler.NavigationMenuRecyclerAdapter;
import ch.pizzalemon.android.api.ApiConstants;
import ch.pizzalemon.android.fragment.CartFragment;
import ch.pizzalemon.android.fragment.OrderHistoryFragment;
import ch.pizzalemon.android.fragment.StoreInfoFragment;
import ch.pizzalemon.android.fragment.MenuFragment;
import ch.pizzalemon.android.fragment.ProductFragment;
import ch.pizzalemon.android.fragment.ProfileFragment;
import ch.pizzalemon.android.helper.DialogHelper;
import ch.pizzalemon.android.helper.DisplayHelper;
import ch.pizzalemon.android.helper.PriceHelper;
import ch.pizzalemon.android.helper.SessionHelper;
import ch.pizzalemon.android.helper.SharedPrefsHelper;
import ch.pizzalemon.android.model.CategoryModel;
import ch.pizzalemon.android.view.AppToolbar;
import io.github.luizgrp.sectionedrecyclerviewadapter.Section;
import io.github.luizgrp.sectionedrecyclerviewadapter.SectionParameters;
import io.github.luizgrp.sectionedrecyclerviewadapter.SectionedRecyclerViewAdapter;

public class MainActivity extends BaseActivity {

    @BindView(R.id.drawerLayout) DrawerLayout drawerLayout;
    @BindView(R.id.navigationMenuRecyclerView) RecyclerView navigationMenuRecyclerView;
    @BindView(R.id.pizzalinkToolbar) AppToolbar appToolbar;
    @BindView(R.id.cartTotalRelativeLayout) RelativeLayout cartTotalRelativeLayout;
    @BindView(R.id.cartTotalTextView) TextView cartTotalTextView;
    @BindView(R.id.minimumPriceTextView) TextView minimumPriceTextView;
    @BindView(R.id.bottomNavigationView) BottomNavigationView bottomNavigationView;

    @BindView(R.id.badgeLayout) RelativeLayout badgeLayout;
    @BindView(R.id.badgeTextView) TextView badgeTextView;

    @BindView(R.id.shoppingCartLayout) LinearLayout shoppingCartLayout;
    @BindView(R.id.shoppingCartButtonLayout) RelativeLayout shoppingCartButtonLayout;
    @BindView(R.id.shoppingCartImageView) ImageView shoppingCartImageView;
    @BindView(R.id.shoppingCartTextView) TextView shoppingCartTextView;

    @BindDrawable(R.drawable.ic_bottom_nav_item_cart_white) Drawable whiteCartDrawable;
    @BindDrawable(R.drawable.ic_bottom_nav_item_cart_yellow) Drawable yellowCartDrawable;

    @BindColor(R.color.pizzalemon_yellow) int yellowColor;
    @BindColor(R.color.white) int whiteColor;

    private FragmentManager fragmentManager;
    private String currentFragmentName = "";
    private String currentCategoryId = "";
    private boolean isStartWithOrderHistory, isStartWithCart;
    private ArrayList<CategoryModel> categoryList = new ArrayList<>();
    private NavigationMenuRecyclerAdapter navigationMenuRecyclerAdapter;
    //private Badge badge;
    private Animation animUp,animDown;

    private SectionedRecyclerViewAdapter sectionAdapter = new SectionedRecyclerViewAdapter();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        getDataFromIntent();
        initViews();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onResume() {
        super.onResume();
        setCartItemCount();
    }

    private void getDataFromIntent(){
        isStartWithOrderHistory = getIntent().getBooleanExtra("isStartWithOrderHistory", false);
        isStartWithCart = getIntent().getBooleanExtra("isStartWithCart", false);
    }

    private void initViews(){
        //initBadgeView();
        initNavigationDrawer();
        initBottomNavigationView();
        showStartScreen();
        setCartItemCount();
        initShoppingCartButton();
        minimumPriceTextView.setText(PriceHelper.getPriceWithCurreny(SessionHelper.getSelectedStore().getMinimumPrice()));
    }

    private void initShoppingCartButton(){

        int shoppingCartLayoutBottomMarginPx = DisplayHelper.dpToPx(20);
        if (DisplayHelper.getNavMode() == NavMode.THREE_BUTTON){
            shoppingCartLayoutBottomMarginPx = DisplayHelper.dpToPx(40);
        }
        ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) shoppingCartLayout.getLayoutParams();
        params.bottomMargin = shoppingCartLayoutBottomMarginPx; // px cinsinden


        animDown = AnimationUtils.loadAnimation(this, R.anim.anim_scale_down);
        animUp = AnimationUtils.loadAnimation(this, R.anim.anim_scale_up);

        shoppingCartButtonLayout.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case (android.view.MotionEvent.ACTION_DOWN):
                        shoppingCartButtonLayout.startAnimation(animDown);
                        return false;
                    case (android.view.MotionEvent.ACTION_UP):
                        shoppingCartButtonLayout.startAnimation(animUp);
                        return false;
                    case (android.view.MotionEvent.ACTION_CANCEL):
                        shoppingCartButtonLayout.startAnimation(animUp);
                }
                return false;
            }
        });

        shoppingCartButtonLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!SessionHelper.isCustomerLoggedIn()){
                    DialogHelper.showNeedToLoginDialog(R.string.need_to_login_for_that_part);
                    return;
                }
                bottomNavigationView.setSelectedItemId(R.id.action_empty);
            }
        });
    }

    /*
    private void initBadgeView(){
        badge = new QBadgeView(this)
                .setBadgeBackgroundColor(yellowColor)
                .setBadgeTextColor(whiteColor)
                .setBadgeGravity(Gravity.TOP | Gravity.END);
    }
    */

    private void showStartScreen(){
        fragmentManager = getSupportFragmentManager();
        if(isStartWithOrderHistory){
            bottomNavigationView.setSelectedItemId(R.id.action_history);
        }
        else if(isStartWithCart){
            bottomNavigationView.setSelectedItemId(R.id.action_empty);
        }
        else {
            openProductsScreen(getDefaultCategory());
        }
    }
    private void initBottomNavigationView(){

        /*
        bottomNavigationView.enableShiftingMode(false);
        bottomNavigationView.setTextSize(10);
        bottomNavigationView.enableItemShiftingMode(false);
        bottomNavigationView.setTextVisibility(true);
         */
        //bottomNavigationView.setItemIconSize(24);

        bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                switch (item.getItemId()){
                    case R.id.action_menu:
                        /*
                        if (currentFragmentName.equals(MenuFragment.FRAGMENT_NAME))
                            return true;
                        fragmentManager.beginTransaction().replace(R.id.fragmentContainer,
                                MenuFragment.newInstance(categoryList.get(ApiConstants.NAVIGATION_MENU_DEFAULT_CATEGORY_INDEX))).commit();
                        currentFragmentName = MenuFragment.FRAGMENT_NAME;
                        */

                        openProductsScreen(getDefaultCategory());

                        shoppingCartImageView.setImageDrawable(whiteCartDrawable);
                        shoppingCartTextView.setTextColor(whiteColor);

                        if(!SessionHelper.isCustomerLoggedIn()) {
                            cartTotalRelativeLayout.setVisibility(View.GONE);
                            return true;
                        }

                        /*
                        if(!SharedPrefsHelper.getCartTotalPrice().equals("0") &&
                                !SharedPrefsHelper.getCartTotalPrice().equals("0.0") &&
                                !SharedPrefsHelper.getCartTotalPrice().equals("0.00")){
                            cartTotalTextView.setText(PriceHelper.getPriceWithCurreny(SharedPrefsHelper.getCartTotalPrice()));
                            cartTotalRelativeLayout.setVisibility(View.VISIBLE);
                        }
                        */

                        cartTotalRelativeLayout.setVisibility(View.VISIBLE);

                        return true;

                    case R.id.action_empty:
                        if(!SessionHelper.isCustomerLoggedIn()){
                            DialogHelper.showNeedToLoginDialog(R.string.need_to_login_for_that_part);
                            return false;
                        }
                        if (currentFragmentName.equals(CartFragment.FRAGMENT_NAME))
                            return true;
                        fragmentManager.beginTransaction().replace(R.id.fragmentContainer, CartFragment.newInstance()).commit();
                        currentFragmentName = CartFragment.FRAGMENT_NAME;

                        currentCategoryId = "";

                        cartTotalRelativeLayout.setVisibility(View.GONE);
                        shoppingCartImageView.setImageDrawable(yellowCartDrawable);
                        shoppingCartTextView.setTextColor(yellowColor);

                        return true;

                    case R.id.action_history:
                        if(!SessionHelper.isCustomerLoggedIn()){
                            DialogHelper.showNeedToLoginDialog(R.string.need_to_login_for_that_part);
                            return false;
                        }
                        if (currentFragmentName.equals(OrderHistoryFragment.FRAGMENT_NAME))
                            return true;
                        fragmentManager.beginTransaction().replace(R.id.fragmentContainer, OrderHistoryFragment.newInstance()).commit();
                        currentFragmentName = OrderHistoryFragment.FRAGMENT_NAME;

                        currentCategoryId = "";

                        cartTotalRelativeLayout.setVisibility(View.GONE);
                        shoppingCartImageView.setImageDrawable(whiteCartDrawable);
                        shoppingCartTextView.setTextColor(whiteColor);

                        return true;

                    case R.id.action_profile:
                        if(!SessionHelper.isCustomerLoggedIn()){
                            DialogHelper.showNeedToLoginDialog(R.string.need_to_login_for_that_part);
                            return false;
                        }
                        if (currentFragmentName.equals(ProfileFragment.FRAGMENT_NAME))
                            return true;
                        fragmentManager.beginTransaction().replace(R.id.fragmentContainer, ProfileFragment.newInstance()).commit();
                        currentFragmentName = ProfileFragment.FRAGMENT_NAME;

                        currentCategoryId = "";

                        cartTotalRelativeLayout.setVisibility(View.GONE);
                        shoppingCartImageView.setImageDrawable(whiteCartDrawable);
                        shoppingCartTextView.setTextColor(whiteColor);

                        return true;

                    case R.id.action_info:
                        if (currentFragmentName.equals(StoreInfoFragment.FRAGMENT_NAME))
                            return true;
                        fragmentManager.beginTransaction().replace(R.id.fragmentContainer, StoreInfoFragment.newInstance()).commit();
                        currentFragmentName = StoreInfoFragment.FRAGMENT_NAME;

                        currentCategoryId = "";

                        cartTotalRelativeLayout.setVisibility(View.GONE);
                        shoppingCartImageView.setImageDrawable(whiteCartDrawable);
                        shoppingCartTextView.setTextColor(whiteColor);

                        return true;
                }
                return false;
            }
        });
    }

    private void initNavigationDrawer(){

        initNavigationMenuRecyclerView();

        appToolbar.getHamburgerIcon().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(drawerLayout.isDrawerOpen(GravityCompat.START))
                    drawerLayout.closeDrawers();
                else
                    openNavigationDrawer();
            }
        });
    }

    private void openNavigationDrawer(){
        drawerLayout.openDrawer(GravityCompat.START);
    }

    public void setPizzalinkToolbarFields(boolean showHamburgerIcon, String title){
        appToolbar.setHamburgerIconVisibility(showHamburgerIcon);
        appToolbar.setTitle(title);
        if(showHamburgerIcon)
            drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
        else
            drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
    }

    private void initNavigationMenuRecyclerView(){
        categoryList = SharedPrefsHelper.readCategoryList();

        for(int i = 0; i < categoryList.size(); i++){
            List<CategoryModel> subcategoryList = categoryList.get(i).getSubCategoryList();
            sectionAdapter.addSection(new CategorySection(i, categoryList.get(i).getName(), subcategoryList));
        }

        navigationMenuRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        navigationMenuRecyclerView.setAdapter(sectionAdapter);
    }

    private class CategorySection extends Section {

        String title;
        List<CategoryModel> list;
        int pstn;

        CategorySection(int pstn, String title, List<CategoryModel> list) {
            super(SectionParameters.builder()
                    .itemResourceId(R.layout.row_subcategory)
                    .headerResourceId(R.layout.row_category)
                    .build());

            this.title = title;
            this.list = list;
            this.pstn = pstn;
        }

        private class HeaderViewHolder extends RecyclerView.ViewHolder {
            private final View rootView;
            private final TextView categoryNameItem;
            private final View bottomLineView;

            HeaderViewHolder(View view) {
                super(view);
                rootView = view;
                categoryNameItem = (TextView) view.findViewById(R.id.categoryNameItem);
                bottomLineView = view.findViewById(R.id.bottomLineView);
            }
        }

        private class ItemViewHolder extends RecyclerView.ViewHolder {

            private final View rootView;
            private final TextView subcategoryNameItem;
            private final View bottomLineView;

            ItemViewHolder(View view) {
                super(view);
                rootView = view;
                subcategoryNameItem = (TextView) view.findViewById(R.id.subcategoryNameItem);
                bottomLineView = (View) view.findViewById(R.id.bottomLineView);
            }
        }

        @Override
        public RecyclerView.ViewHolder getHeaderViewHolder(View view) {
            return new HeaderViewHolder(view);
        }

        @Override
        public RecyclerView.ViewHolder getItemViewHolder(View view) {
            return new ItemViewHolder(view);
        }

        @Override
        public void onBindHeaderViewHolder(RecyclerView.ViewHolder holder) {
            final HeaderViewHolder headerHolder = (HeaderViewHolder) holder;
            headerHolder.categoryNameItem.setText(title);

            headerHolder.rootView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    openProductsScreen(categoryList.get(pstn));
                }
            });

            if(pstn == categoryList.size() - 1){
                headerHolder.bottomLineView.setVisibility(View.GONE);
                return;
            }

            if(categoryList.get(pstn).getSubCategoryList() == null ||
                    categoryList.get(pstn).getSubCategoryList().size() == 0){
                headerHolder.bottomLineView.setVisibility(View.VISIBLE);
            }else {
                headerHolder.bottomLineView.setVisibility(View.GONE);
            }

        }

        @Override
        public void onBindItemViewHolder(RecyclerView.ViewHolder holder, final int position) {
            final ItemViewHolder itemHolder = (ItemViewHolder) holder;
            String name = list.get(position).getName();
            itemHolder.subcategoryNameItem.setText(name);
            if(position == list.size() - 1){
                itemHolder.bottomLineView.setVisibility(View.VISIBLE);
            }
            else {
                itemHolder.bottomLineView.setVisibility(View.GONE);
            }
            itemHolder.rootView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    openProductsScreen(list.get(position));
                }
            });
        }

        @Override
        public int getContentItemsTotal() {
            return list.size();
        }
    }

    private void openProductsScreen(CategoryModel clickedCategoryModel){

        if(clickedCategoryModel.getId().equals(ApiConstants.PRODUCT_ID_VERSION_MENU)){
            return;
        }

        drawerLayout.closeDrawers();

        if(clickedCategoryModel.isSpecialCategory()){

            if(currentFragmentName.equals(ProductFragment.FRAGMENT_NAME) &&
                    currentCategoryId == clickedCategoryModel.getId())
                return;

            fragmentManager.beginTransaction().replace(R.id.fragmentContainer,
                    ProductFragment.newInstance(clickedCategoryModel)).commit();
            currentFragmentName = ProductFragment.FRAGMENT_NAME;
            currentCategoryId = clickedCategoryModel.getId();
        }
        else {

            if(currentFragmentName.equals(MenuFragment.FRAGMENT_NAME) &&
                    currentCategoryId == clickedCategoryModel.getId())
                return;


            fragmentManager.beginTransaction().replace(R.id.fragmentContainer,
                    MenuFragment.newInstance(clickedCategoryModel)).commit();
            currentFragmentName = MenuFragment.FRAGMENT_NAME;
            currentCategoryId = clickedCategoryModel.getId();
        }

    }

    public void setCartItemCount(){
        updateBadge();
        updateCartTotalRelativeLayout();
    }

    public void reopenCartFragment(){
        currentFragmentName = "";
        bottomNavigationView.setSelectedItemId(R.id.action_empty);
    }

    /*
    private void addBadge(int position, int number) {
        badge.setBadgeNumber(number);
        badge.bindTarget(bottomNavigationView.getBottomNavigationItemView(position));
    }
    */

    private void updateCartTotalRelativeLayout() {

        if(!SessionHelper.isCustomerLoggedIn()) {
            cartTotalRelativeLayout.setVisibility(View.GONE);
            return;
        }

        /*
        if(SharedPrefsHelper.getCartTotalPrice().equals("0") ||
                SharedPrefsHelper.getCartTotalPrice().equals("0.0") ||
                SharedPrefsHelper.getCartTotalPrice().equals("0.00")){
            cartTotalRelativeLayout.setVisibility(View.GONE);
        }
        else {
            cartTotalTextView.setText(PriceHelper.getPriceWithCurreny(SharedPrefsHelper.getCartTotalPrice()));
            cartTotalRelativeLayout.setVisibility(View.VISIBLE);
        }
        */

        cartTotalTextView.setText(PriceHelper.getPriceWithCurreny(SharedPrefsHelper.getCartTotalPrice()));
        if(getSupportFragmentManager().findFragmentById(R.id.fragmentContainer) != null &&
                getSupportFragmentManager().findFragmentById(R.id.fragmentContainer) instanceof MenuFragment){
            cartTotalRelativeLayout.setVisibility(View.VISIBLE);
        }

    }

    public void updateBadge(){

        if(!SessionHelper.isCustomerLoggedIn()) {
            badgeLayout.setVisibility(View.GONE);
            return;
        }

        int count = SharedPrefsHelper.getCartItemCount();
        badgeTextView.setText(String.valueOf(count));

        if(count <= 0){
            badgeLayout.setVisibility(View.GONE);
        }
        else {
            badgeLayout.setVisibility(View.VISIBLE);
        }
    }

    public void openFragmentAt(int position){
        currentFragmentName = "";
        int menuItemId;
        switch (position){
            case 0:
                menuItemId = R.id.action_menu;
                break;
            case 1:
                menuItemId = R.id.action_history;
                break;
            case 3:
                menuItemId = R.id.action_profile;
                break;
            case 4:
                menuItemId = R.id.action_info;
                break;
            default:
                menuItemId = R.id.action_empty;
                break;
        }
        bottomNavigationView.setSelectedItemId(menuItemId);
    }

    public void setCartTotalLayoutVisibility(boolean isVisible){

        if(!SessionHelper.isCustomerLoggedIn()) {
            cartTotalRelativeLayout.setVisibility(View.GONE);
            return;
        }

        if(isVisible){
            cartTotalRelativeLayout.setVisibility(View.VISIBLE);
        }
        else {
            cartTotalRelativeLayout.setVisibility(View.GONE);
        }
    }

    private CategoryModel getDefaultCategory(){
        CategoryModel defaultCategory = null;
        for(CategoryModel categoryModel: categoryList){
            if(categoryModel.isDefault()){
                defaultCategory = categoryModel;
                break;
            }
        }
        if(defaultCategory == null){
            for(CategoryModel categoryModel: categoryList){
                if(categoryModel.getName().trim().toLowerCase().equals("pizza")){
                    defaultCategory = categoryModel;
                    break;
                }
            }
        }
        if(defaultCategory == null){
            defaultCategory = categoryList.get(0);
        }
        return defaultCategory;
    }

}
