package com.pixelnx.localhelp.ui.home;


import android.content.DialogInterface;
import android.content.Intent;


import android.os.Bundle;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;



import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.room.Room;

import com.androidnetworking.AndroidNetworking;
import com.androidnetworking.common.Priority;
import com.androidnetworking.error.ANError;
import com.androidnetworking.interfaces.ParsedRequestListener;

import com.bumptech.glide.Glide;
import com.pixelnx.localhelp.R;
import com.pixelnx.localhelp.model.ModelShopListData;

import com.pixelnx.localhelp.spash.Database;
import com.pixelnx.localhelp.spash.Modellogo;
import com.pixelnx.localhelp.ui.base.ActivityBase;
import com.pixelnx.localhelp.ui.order.ActivityOrderCart;
import com.pixelnx.localhelp.ui.user.ActivityProfileSetting;
import com.pixelnx.localhelp.utils.Consts;
import com.pixelnx.localhelp.utils.ProjectUtils;
import com.pixelnx.localhelp.utils.sharedpref.SharedPref;
import com.pixelnx.localhelp.utils.widgets.CustomEditText;
import com.pixelnx.localhelp.utils.widgets.CustomTextBold;

import com.pixelnx.localhelp.utils.widgets.CustomTextMedium;



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


public class ActivityCategHome extends ActivityBase implements View.OnClickListener {


     CustomEditText etSearch;
    CustomTextBold title;

    Database dateBase;
    Modellogo modellogo;
    ImageView shopIv;
    ImageView sideDrawer;
    ImageView profileIv;

    CardView rvOrderRes;

    static ModelShopListData.Data data;


    RecyclerView rvCatItems;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentBaseView(R.layout.activity_customer_hometwo);

        mContext = ActivityCategHome.this;


        sharedPref = SharedPref.getInstance(mContext);
        modelUserData = sharedPref.getUser(Consts.Status.SP);
        profileIv=findViewById(R.id.profileIv);
        rvOrderRes = findViewById(R.id.rvorderRes);




        profileIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent(mContext, ActivityProfileSetting.class);
                startActivity(intent);

            }
        });



        initial();
    }




    private void initial() {


        rvCatItems= findViewById(R.id.rvCatItems);
        rvCatItems.setLayoutManager(new GridLayoutManager(mContext, 3));
        cat();
        title = findViewById(R.id.title);
        dateBase = Room.databaseBuilder
                (getApplicationContext(),
                        Database.class, "database-name").fallbackToDestructiveMigration()
                .allowMainThreadQueries().build();
        modellogo=new Modellogo();
        modellogo= dateBase.daoAccess().getAllSetData();
        if(!modellogo.getLogoTitle().isEmpty()){
            title.setText(String.valueOf(modellogo.getLogoTitle()));}



        shopIv = findViewById(R.id.shopIv);

        sideDrawer = findViewById(R.id.sideDrawer);
        sideDrawer.setOnClickListener(this);
        etSearch = findViewById(R.id.etSearch);
        etSearch.setOnClickListener(this);
        shopIv.setOnClickListener(this);

        if(getIntent().hasExtra("data")){

            if(data == null){
                data= (ModelShopListData.Data) getIntent().getSerializableExtra("data");
            }else{
                if(!data.getUserId().equalsIgnoreCase(""+getIntent().getStringExtra("chk_shp"))){
                    if(dataArrayList.size() != 0){
                        exitCartRemove();}else{
                        data= (ModelShopListData.Data) getIntent().getSerializableExtra("data");
                    }
                }
            }


        }



    }
    void cat(){
        ProjectUtils.showProgressDialog(mContext, false, "Loading...");
        AndroidNetworking.post(Consts.Status.BASE_URL + Consts.Status.ALLCATEGORY_API)
                .setPriority(Priority.IMMEDIATE)
                .setTag(Consts.Status.SEARCH_API)
                .build()
                .getAsObject(ModelCategHome.class, new ParsedRequestListener<ModelCategHome>() {
                    @Override
                    public void onResponse(ModelCategHome response) {
                     if(response.getStatus().equalsIgnoreCase("1")){
                      AdapterCategory adapterCategory=new AdapterCategory(response.getCategoryData());
                           rvCatItems.setAdapter(adapterCategory);
                          }
                        ProjectUtils.pauseProgressDialog();
                         }

                    @Override
                    public void onError(ANError anError) {
                        ProjectUtils.pauseProgressDialog();

                    }
                });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.sideDrawer:
                onBackPressed();

                break;
            case R.id.etSearch:
                Intent intent=new Intent(mContext,ActivityHome.class);
                intent.putExtra("data",data);
                startActivity(intent);
                break;
            case R.id.shopIv:



                if(dataArrayList.isEmpty()){

                congratsDialog();}
                else{
                    Intent intentShop=new Intent(mContext, ActivityOrderCart.class);
                    startActivity(intentShop);
                }

                break;




        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        if(dataArrayList==null){
            dataArrayList=new ArrayList<>();}else{
            tvOrderTotal.setText("Total item " + dataArrayList.size() + "  |  " + total + " Rs");
            if(dataArrayList.isEmpty()){
                rvOrderRes.setVisibility(View.GONE);
            }else {
                rvOrderRes.setVisibility(View.VISIBLE);
            }
        }

    }



    private void exitCartRemove() {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);

        builder.setMessage("Are you sure you want cancel previous order?\nFrom "+data.getUserName())
                .setCancelable(false)
                .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        data= (ModelShopListData.Data) getIntent().getSerializableExtra("data");
                        dataArrayList = new ArrayList<>();
                        total=0;
                        tvOrderTotal.setText("Total item " + dataArrayList.size() + "  |  " + 0 + " Rs");
                    }
                })
                .setNegativeButton("No", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });

        AlertDialog alertDialog = builder.create();
        alertDialog.show();
    }


    public class AdapterCategory extends RecyclerView.Adapter<HolderAdapterQuestionList> {

        List<ModelCategHome.Data> list;

        View view;

        public AdapterCategory(List<ModelCategHome.Data> list) {
            this.list= list;


        }

        @NonNull
        @Override
        public HolderAdapterQuestionList onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
            view = LayoutInflater.from(mContext).inflate(R.layout.cat_items, viewGroup, false);

            return new HolderAdapterQuestionList(view);

        }

        @Override
        public void onBindViewHolder(@NonNull HolderAdapterQuestionList holder, final int i) {
String nameCat=""+list.get(i).getCatName();
            holder.catName.setText(nameCat);
            Glide
                    .with(mContext)
                    .load(Consts.Status.BASE_IMAGE_URL+list.get(i).getCatImage())
                    .override(200, 200)
                    .fitCenter()
                    .placeholder(R.drawable.noimage)
                    .into(holder.img);

            holder.img.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intentCat=new Intent(mContext, ActivityHome.class);
                    intentCat.putExtra("tag",""+list.get(i).getCatName());
                    intentCat.putExtra("data",data);
                    intentCat.putExtra("catId",""+list.get(i).getCatId());
                    mContext.startActivity(intentCat);
                }
            });
        }



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

        @Override
        public int getItemViewType(int position) {
            return position;
        }

    }

    public static class HolderAdapterQuestionList extends RecyclerView.ViewHolder {

        CustomTextMedium catName;
        ImageView img;

        public HolderAdapterQuestionList(@NonNull View itemView) {
            super(itemView);
            catName = itemView.findViewById(R.id.catName);
            img = itemView.findViewById(R.id.img);

        }
    }
}
