package com.droideve.apps.dealify.activities;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.content.res.AppCompatResources;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;

import com.droideve.apps.dealify.R;
import com.droideve.apps.dealify.appconfig.Constances;
import com.droideve.apps.dealify.classes.Category;
import com.droideve.apps.dealify.classes.Store;
import com.droideve.apps.dealify.controllers.categories.CategoryController;
import com.droideve.apps.dealify.controllers.stores.StoreController;
import com.droideve.apps.dealify.fragments.ListOffersFragment;
import com.droideve.apps.dealify.fragments.ListProductsFragment;
import com.droideve.apps.dealify.fragments.ListStoresFragment;

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

import butterknife.ButterKnife;
import io.realm.RealmResults;
import scala.Int;

public class ResultFilterActivity extends GlobalActivity {

    Toolbar toolbar;
    private HashMap<String, Object> searchParams;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_result_filter);
        ButterKnife.bind(this);

        initToolbar();

        if (getIntent().getExtras().containsKey("searchParams"))
            handleResultSearchByModule((HashMap<String, Object>) getIntent().getExtras().getSerializable("searchParams"));
        else
            onBackPressed();

    }


    private void handleResultSearchByModule(HashMap<String, Object> _searchParams) {

        //fill params
        searchParams = _searchParams;

        Bundle b = new Bundle();
        b.putSerializable("searchParams", _searchParams);
        Fragment fragResult = null;

        if (_searchParams.containsKey("module") && _searchParams.get("module").equals(Constances.ModulesConfig.STORE_MODULE)) {
            getAppBarTitle().setText(getString(R.string.stores_result));
            fragResult = new ListStoresFragment();
        } else if (_searchParams.containsKey("module") && _searchParams.get("module").equals(Constances.ModulesConfig.PRODUCT_MODULE)) {
            getAppBarTitle().setText(getString(R.string.products_result));
            fragResult = new ListProductsFragment();
        } else if (_searchParams.containsKey("module") && _searchParams.get("module").equals(Constances.ModulesConfig.OFFER_MODULE)) {
            getAppBarTitle().setText(getString(R.string.offers_result));
            fragResult = new ListOffersFragment();
        }

        if (_searchParams.containsKey("custom_title") && _searchParams.get("custom_title") != null) {
            getAppBarTitle().setText(_searchParams.get("custom_title").toString());
        }

        if (_searchParams.containsKey("custom_sub_title") && _searchParams.get("custom_sub_title") != null) {
            getAppBarTitle().setText(_searchParams.get("custom_sub_title").toString());
            getAppBarTitle().setVisibility(View.VISIBLE);
        }
            FragmentManager manager = getSupportFragmentManager();
        if (fragResult != null) {
            fragResult.setArguments(b);
            manager.beginTransaction()
                    .replace(R.id.result_layout, fragResult)
                    .commit();
        } else {
            onBackPressed();
        }


        setupCategoryFilter();


        if(searchParams.containsKey("store_id")){
            getAppBarTitle().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(ResultFilterActivity.this, StoreDetailActivity.class);
                    String storeId = (String) searchParams.get("store_id");
                    intent.putExtra("id", Integer.parseInt(storeId));
                    startActivity(intent);
                }
            });

            try {
                String storeId = (String) searchParams.get("store_id");
                Store store = StoreController.findStoreById(  Integer.parseInt( storeId) );
                if(store!=null){
                    getAppBarSubtitle().setVisibility(View.VISIBLE);
                    getAppBarSubtitle().setText(store.getAddress());
                }
            }catch (Exception e){
                e.printStackTrace();
            }

        }



    }

    int defaultCat = 0;

    private void updateResultsForCatFilter(int catId){

        if(catId == -1){
            catId = defaultCat;
        }

        Category category = CategoryController.findId(catId);

        if(category==null)
            return;

        //fill params
        searchParams.put("category_id",catId);

        Bundle b = new Bundle();
        b.putSerializable("searchParams", searchParams);
        Fragment fragResult = null;

        if (searchParams.containsKey("module") && searchParams.get("module").equals(Constances.ModulesConfig.STORE_MODULE)) {
            fragResult = new ListStoresFragment();
        } else if (searchParams.containsKey("module") && searchParams.get("module").equals(Constances.ModulesConfig.PRODUCT_MODULE)) {
            fragResult = new ListProductsFragment();
        } else if (searchParams.containsKey("module") && searchParams.get("module").equals(Constances.ModulesConfig.OFFER_MODULE)) {
            fragResult = new ListOffersFragment();
        }


        getAppBarTitle().setText( String.format(getString(R.string.result_for), category.getNameCat())  );

        FragmentManager manager = getSupportFragmentManager();
        if (fragResult != null) {
            fragResult.setArguments(b);
            manager.beginTransaction()
                    .replace(R.id.result_layout, fragResult)
                    .commit();
        } else {
            onBackPressed();
        }


    }

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

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.home_menu, menu);

        menu.findItem(R.id.search_icon).setVisible(true);

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        if (android.R.id.home == item.getItemId()) {
            finish();
        } else if (item.getItemId() == R.id.search_icon) {
            Intent intent = new Intent(this, CustomSearchActivity.class);
            intent.putExtra("useCacheFields", "enabled");
            intent.putExtra("searchParams", searchParams);
            startActivityForResult(intent, 50505);
            //finish();
        }

        return super.onOptionsItemSelected(item);
    }


    public void initToolbar() {

        toolbar = findViewById(R.id.app_bar);
        setupToolbar(toolbar);
        getAppBarSubtitle().setVisibility(View.GONE);

    }

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

        if (50505 == requestCode && resultCode == Activity.RESULT_OK) {
            searchParams = (HashMap<String, Object>) data.getExtras().getSerializable("searchParams");
            handleResultSearchByModule(searchParams);
        }
    }


    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {

        menu.findItem(R.id.list_view_icon).setVisible(true);
        menu.findItem(R.id.search_icon).setVisible(true);
        menu.findItem(R.id.notification_action).setVisible(false);
        menu.findItem(R.id.cart_icon).setVisible(false);

        super.onPrepareOptionsMenu(menu);


        return false;
    }



    private List<Category> listCats = new ArrayList<>();


    @SuppressLint("ResourceType")
    private void setupCategoryFilter() {


        if(!searchParams.containsKey("category_id"))
            return;

        int catId = 0;

        try {
            catId = (int) searchParams.get("category_id");
        }catch (Exception e){
            return;
        }

        Category category = CategoryController.findId(catId);

        if(category == null)
            return;

        RealmResults<Category> cats = CategoryController.findByParent(catId);

        if(cats.size()==0)
            return;


        defaultCat = catId;

        HorizontalScrollView scrollView = findViewById(R.id.categoryWrapper);

        LinearLayout.LayoutParams customParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        customParams.setMargins(
                0,
                (int) getResources().getDimension(R.dimen.spacing_small),
                0,
                (int) getResources().getDimension(R.dimen.spacing_small));

        LinearLayout rowBtns = new LinearLayout(this);
        rowBtns.setOrientation(LinearLayout.HORIZONTAL);
        rowBtns.setLayoutParams(customParams);

        //get the list of group title first

        listCats.addAll(cats);

        //add all cat first
        Category all_categories_menu = new Category(-1,
                getString(R.string.all_categories_menu), 0, null);
        listCats.add(0, all_categories_menu);

        for (Category cat : listCats) {

            Button catBtn = new Button(this);
            catBtn.setPadding(
                    (int) getResources().getDimension(R.dimen.spacing_large),
                    0,
                    (int) getResources().getDimension(R.dimen.spacing_large),
                    0);

            LinearLayout.LayoutParams catBtnLP = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, (int) getResources().getDimension(R.dimen.button_height_size1));
            catBtnLP.setMargins(
                    0,
                    (int) 0,
                    (int) getResources().getDimension(R.dimen.spacing_medium),
                    (int) 0
            );
            catBtn.setLayoutParams(catBtnLP);

            catBtn.setBackground(ContextCompat.getDrawable(this, R.drawable.btn_rect_outline_white));

            int valueInPixels = (int) (getResources().getDimension(R.dimen.title_size_small) / getResources().getDisplayMetrics().density);
            catBtn.setTextSize(TypedValue.COMPLEX_UNIT_DIP, valueInPixels);
            catBtn.setTextColor(AppCompatResources.getColorStateList(this, R.drawable.btn_rect_outline_text_white));
            catBtn.setText(cat.getNameCat());
            catBtn.setTag(cat.getNumCat());
            catBtn.setId(cat.getNumCat());

            catBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    for (int i = 0; i < listCats.size(); i++) {
                        if (view.getId() == listCats.get(i).getNumCat()) {
                            rowBtns.findViewWithTag(listCats.get(i).getNumCat()).setSelected(true);
                           int  CATEGORY_SELECTED = cat.getNumCat();
                            updateResultsForCatFilter(CATEGORY_SELECTED);
                        } else {
                            rowBtns.findViewWithTag(listCats.get(i).getNumCat()).setSelected(false);
                        }
                    }
                }
            });

            rowBtns.addView(catBtn);
        }


        //Category Listener


        scrollView.addView(rowBtns);


    }



}
