package com.qboxus.tictic.activitesfragments.sendgift;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import com.qboxus.tictic.Constants;
import com.qboxus.tictic.R;
import com.qboxus.tictic.activitesfragments.walletandwithdraw.MyWallet;
import com.qboxus.tictic.apiclasses.ApiLinks;
import com.qboxus.tictic.interfaces.FragmentCallBack;
import com.qboxus.tictic.models.UserModel;
import com.qboxus.tictic.simpleclasses.DataParsing;
import com.qboxus.tictic.simpleclasses.Dialogs;
import com.qboxus.tictic.simpleclasses.Functions;
import com.qboxus.tictic.simpleclasses.Variables;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.android.material.bottomsheet.BottomSheetDialogFragment;
import com.smarteist.autoimageslider.SliderView;
import com.volley.plus.VPackages.VolleyRequest;
import com.volley.plus.interfaces.Callback;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import io.paperdb.Paper;

/**
 * A simple {@link Fragment} subclass.
 */
public class StickerGiftFragment extends BottomSheetDialogFragment {

    View view;
    Context context;
    TextView coins_txt;
    double total_coins = 0;
    SendGiftVHAdapter giftSliderAdapter;
    List<List<StickerModel>> sliderList = new ArrayList<>();
    List<StickerModel> data_list = new ArrayList<>();
    StickerModel selectedModel;
    ProgressBar progressBar;
    SliderView imageSlider;

    String id, name, image;

    FragmentCallBack callBack;
    BottomSheetDialog dialog;
    private BottomSheetBehavior mBehavior;

    public StickerGiftFragment() {

    }

    public StickerGiftFragment(String id, String name, String image, FragmentCallBack callBack) {
        this.id = id;
        this.name = name;
        this.image = image;
        this.callBack = callBack;
    }


    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        dialog = (BottomSheetDialog) super.onCreateDialog(savedInstanceState);

        View view = View.inflate(getContext(), R.layout.fragment_sticker_gift, null);
        dialog.setContentView(view);

        mBehavior = BottomSheetBehavior.from((View) view.getParent());

        mBehavior.setPeekHeight((int) view.getContext().getResources().getDimension(R.dimen._550sdp), true);
        mBehavior.addBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
            @Override
            public void onStateChanged(@NonNull View bottomSheet, int newState) {
                if (newState != BottomSheetBehavior.STATE_EXPANDED) {
                    mBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);
                }
            }

            @Override
            public void onSlide(@NonNull View bottomSheet, float slideOffset) {

            }
        });
        return dialog;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        view = inflater.inflate(R.layout.fragment_sticker_gift, container, false);
        context = getContext();

        coins_txt = view.findViewById(R.id.coins_txt);
        progressBar = view.findViewById(R.id.progressBar);
        String wallet = Functions.getSharedPreference(view.getContext()).getString(Variables.U_WALLET, "0");
        total_coins = Double.parseDouble(wallet);
        coins_txt.setText(wallet);
        imageSlider = view.findViewById(R.id.imageSlider);
        SetUpGiftSliderAdapter();

        view.findViewById(R.id.recharge_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
                startActivity(new Intent(getActivity(), MyWallet.class));
            }
        });

        hitSHowGiftScreen();
        return view;

    }

    public void sendGiftAction() {


        for (StickerModel model : data_list) {
            if (model.isSelected) {

                double coin_required = (Double.valueOf(model.coins) * 1);
                if (total_coins >= coin_required) {

                    Bundle bundle = new Bundle();
                    bundle.putBoolean("isShow", false);
                    bundle.putBoolean("showCount", true);
                    bundle.putString("count", "1");
                    bundle.putSerializable("Data", selectedModel);
                    callBack.onResponce(bundle);


                    Call_api_Send_sticker(model, 1);

                } else {
                    Toast.makeText(getActivity(), context.getString(R.string.you_dont_have_sufficent_coins), Toast.LENGTH_SHORT).show();
                }

            }
        }

    }

    private void hitSHowGiftScreen() {
        {
            if (Paper.book("Gift").contains("giftList")) {
                data_list.clear();
                data_list.addAll(Paper.book("Gift").read("giftList"));
                sliderList.clear();
                sliderList.addAll(Functions.createChunksOfList(data_list, 12));
                giftSliderAdapter.notifyDataSetChanged();
            }
        }
        if (data_list.size() < 1) {
            progressBar.setVisibility(View.VISIBLE);
        }

        JSONObject jsonObject = new JSONObject();
        VolleyRequest.JsonPostRequest(getActivity(), ApiLinks.showGifts, jsonObject, Functions.getHeaders(getActivity()), new Callback() {
            @Override
            public void onResponce(String resp) {
                Functions.checkStatus(getActivity(), resp);
                progressBar.setVisibility(View.GONE);
                if (resp != null) {

                    try {

                        JSONObject jsonObject = new JSONObject(resp);

                        String code = jsonObject.optString("code");
                        if (code != null && code.equals("200")) {
                            JSONArray msgarray = jsonObject.getJSONArray("msg");

                            data_list.clear();
                            for (int i = 0; i < msgarray.length(); i++) {
                                JSONObject giftArray = msgarray.getJSONObject(i);
                                JSONObject giftObj = giftArray.getJSONObject("Gift");
                                StickerModel model = new StickerModel();
                                model.id = giftObj.optString("id");
                                model.image = giftObj.optString("image");
                                model.name = giftObj.optString("title");
                                model.type = giftObj.optString("type");
                                model.sound = giftObj.optString("sound");
                                model.icon = giftObj.optString("icon");
                                model.time = giftObj.optString("time", "0");
                                model.coins = giftObj.optString("coin", "0");
                                model.isSelected = false;
                                model.count = 0;
                                data_list.add(model);
                            }


                            Paper.book("Gift").write("giftList", data_list);


                            {
                                data_list.clear();

                                data_list.addAll(Paper.book("Gift").read("giftList"));

                                sliderList.clear();
                                sliderList.addAll(Functions.createChunksOfList(data_list, 12));
                                giftSliderAdapter.notifyDataSetChanged();
                            }

                        } else {
                            Dialogs.showAlert(getActivity(), getActivity().getApplicationContext().getString(R.string.server_error), jsonObject.optString("msg", "Our technical team work on this issue"));

                        }

                    } catch (Exception e) {
                        Log.d(Constants.tag, "Exception : " + e);
                    }

                }

            }
        });


    }

    private void SetUpGiftSliderAdapter() {
        sliderList.clear();
        sliderList.addAll(Functions.createChunksOfList(data_list, 12));
        giftSliderAdapter = new SendGiftVHAdapter(sliderList, new FragmentCallBack() {
            @Override
            public void onResponce(Bundle bundle) {
                if (bundle.getBoolean("isShow", false)) {
                    selectedModel = (StickerModel) bundle.getSerializable("Data");
                    if (bundle.getBoolean("isSend", false)) {
                        sendGiftAction();
                    }
                }
            }
        });
        imageSlider.setSliderAdapter(giftSliderAdapter);
    }

    public void Call_api_Send_sticker(StickerModel model, int giftCount) {

        JSONObject params = new JSONObject();
        try {
            params.put("sender_id", Variables.sharedPreferences.getString(Variables.U_ID, ""));
            params.put("receiver_id", id);
            params.put("gift_id", model.id);
            params.put("gift_count", giftCount);
        } catch (Exception e) {
            e.printStackTrace();
        }

        Functions.showLoader(getActivity(), false, false);
        VolleyRequest.JsonPostRequest(getActivity(), ApiLinks.sendGift, params, Functions.getHeaders(getActivity()), new Callback() {
            @Override
            public void onResponce(String resp) {
                Functions.checkStatus(getActivity(), resp);
                Functions.cancelLoader();

                try {
                    JSONObject jsonObject = new JSONObject(resp);
                    String code = jsonObject.optString("code");
                    if (code != null && code.equals("200")) {
                        JSONObject msgObj = jsonObject.getJSONObject("msg");
                        UserModel userDetailModel = DataParsing.getUserDataModel(msgObj.optJSONObject("User"));
                        SharedPreferences.Editor editor = Functions.getSharedPreference(view.getContext()).edit();
                        editor.putString(Variables.U_WALLET, "" + userDetailModel.wallet);
                        editor.commit();

                        Bundle bundle = new Bundle();
                        bundle.putBoolean("isShow", true);
                        bundle.putString("count", "" + giftCount);
                        bundle.putSerializable("Data", model);
                        callBack.onResponce(bundle);
                        dismiss();
                    } else if (code != null && code.equals("201")) {
                        Dialogs.showAlert(getActivity(), getActivity().getApplicationContext().getString(R.string.server_error), jsonObject.optString("msg"));
                    } else
                        Toast.makeText(context, jsonObject.optString("msg"), Toast.LENGTH_SHORT).show();

                } catch (Exception e) {
                    e.printStackTrace();
                }


            }
        });

    }


}
